JDBC Statement Insert record example

JDBC Statement Insert record example

By Yashwant Chavan, Views 963, Date 02-Jun-2012

In this tutorial, You will learn how to Insert record into database table using JDBC Statement. This step by step guide will help you to create database connection, create sql Statement to perform the database insertion operation.

tags java

Jdbc Statement Insert record example

Refer below steps to insert records using JDBC Statement

  • Get the new connection using getConnection() method.
  • Creates a Statement using connection object, which will help you to execute SQL statement.
  • sql Write insert query which will insert record into trn_employee table.
  • Execute Query - Use statement.executeUpdate(sql) method to execute the insert query.
  • Finally release all the resources by calling close() method on Statement and Connection object.
package com.technicalkeeda.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcInsertExample {

    public static void main(String[] args) {

        JdbcInsertExample example = new JdbcInsertExample();
        example.insert();
    }

    public void insert() {

        Statement statement = null;
        Connection connection = null;
        try {

            connection = getConnection();
            statement = connection.createStatement();

            String sql = "insert into trn_employee (emp_id, first_name, last_name,dept) VALUES(1,'Yashwant','Chavan','IT')";

            int affectedRecords = statement.executeUpdate(sql);
            System.out.println("Number of Records Inserted:- " + affectedRecords);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }

                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }

    }

    private Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/technicalkeeda", "root", "");

        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return connection;
    }
}

Output

Number of Records Inserted:- 1
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]