How to insert records in table using jdbc example

In this tutorial you will learn how to insert records in database table using jdbc, normally in database to insert the records in tables we have to create the insert statement for the table for different records to be inserted.

In the same way we have to create the insert statement for the table with data, and that insert statement has to run by jdbc.

In this tutorial we will use the table PERSON which has been created in last tutorial. For information the PERSON table has three columns named as PERSON_ID, NAME and AGE. So we will create the INSERT statement for PERSON table and insert the records using jdbc.

The method executeUpdate() of statement object will be used to execute the INSERT statements.

The INSERT statement we are going to execute using jdbc will be as:

INSERT INTO PERSON VALUES(1, 'RAJENDRA', 35);
INSERT INTO PERSON VALUES(2, 'MAHENDRA', 29);
INSERT INTO PERSON VALUES(3, 'SURENDRA', 22);

Below is the example of JDBC code which will insert the data in table PERSON.

package com.java.connect.jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
 
public class JDBCInsertRecordExample {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
 
        try {
            // Register the mysql driver
            Class.forName("com.mysql.jdbc.Driver"); // Or any other driver which database you want to connect.
            // Get the connection object
            connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
            // Get the statement object
            statement = connection.createStatement();
            // Prepare the INSERT STATEMENTS for PERSON table, in this example we are using the PERSON as table name and it has
            // Three columns as PERSON_ID, NAME and AGE
            String INSERT_1 = "INSERT INTO PERSON VALUES(1, 'RAJENDRA', 35)";
            String INSERT_2 = "INSERT INTO PERSON VALUES(2, 'MAHENDRA', 29)";
            String INSERT_3 = "INSERT INTO PERSON VALUES(3, 'SURENDRA', 22)";
 
            // Run the SQL query and check in database if the
            statement.executeUpdate(INSERT_1);
            statement.executeUpdate(INSERT_2);
            statement.executeUpdate(INSERT_3);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // Finally we have close all the JDBC resources
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}