Inserting records into a MySQL table using Java

To insert records to a MySQL table, you must have a working Java-MySQL connection. If you don't know to connect your Java application with MySQL, read How to connect Java application with MySQL first.

Inserting records into a MySQL table using Java

To insert records to a MySQL table, you must have a working Java-MySQL connection. If you don’t know to connect your Java application with MySQL, read How to connect Java application with MySQL first.

Before continuing, create the following table in your MySQL database.

create table users (
 id int unsigned auto_increment PRIMARY KEY, 
 _name varchar(32) not null, 
 age int not null 
);

First, let us insert a single record to the table.  To do so, follow these steps:

  • Create a new java class.
  • Add the following packages

import java.sql.*;

  • In the main method, add the following code:
try
{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost/javadb","root","");
    String sql="insert into users (_name,age) values (?,?)";
    PreparedStatement st=con.prepareStatement(sql);
    st.setString(1, "mishel");
    st.setString(2, "21");
    st.execute();
    con.close();
    System.out.println("Data inserted");
}
catch(Exception ex)
{
    System.out.println(ex.getMessage());
}

The above program when executed will produce the following output.

Data inserted

Share Tweet Send
0 Comments
Loading...