Inserting records into a MySQL table using Java
Java MySQL Database

Inserting records into a MySQL table using Java

Editorial Team
Editorial Team

Follow us on Discord or Telegram to get access to free tutorials and updates.

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:
    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");
    System.out.println("Data inserted");
catch(Exception ex)

The above program when executed will produce the following output.

Data inserted