Saturday, 19 July 2014

JDBC Insert Record Demo

Enjoying Java & Database Tutorials?

Subscribe to Ram N Java on YouTube for beginner-friendly coding lessons and hands-on demos!

🔔 Subscribe to Channel

How to Insert Records into a Database Using JDBC

Inserting new records into a database table is one of the most fundamental operations in software development. In SQL, this task is handled using the INSERT INTO command. Through JDBC (Java Database Connectivity), Java applications can easily connect to relational databases and insert new rows safely and reliably.

The SQL INSERT INTO Statement

In SQL, you add rows by naming the table, the target columns, and the corresponding values:

INSERT INTO students (id, first_name, last_name, age) VALUES (101, 'John', 'Doe', 21);

This query adds a single new row into the students table.

Step-by-Step Java Implementation

Follow these standard steps to insert records using JDBC:

  1. Establish Connection: Connect to your target database using DriverManager.getConnection().
  2. Create a PreparedStatement: Use parameter placeholders (?) in your SQL string to safeguard against SQL injection.
  3. Set Parameter Values: Bind data to each placeholder using appropriate setter methods like setInt() and setString().
  4. Execute the Statement: Invoke executeUpdate() to send the row to the database and receive the affected row count.
  5. Close Resources: Release the statement and connection objects cleanly using try-with-resources.

Watch More JDBC Tutorials


Click here to watch in Youtube : https://www.youtube.com/watch?v=psa47Zic1Fg

Click the below Image to Enlarge

JDBCInsertRecordDemo Project Dir Structure



JDBCInsertRecord.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCInsertRecord
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";

    // Database credentials
    static final String USERNAME = "root";
    static final String PASSWORD = "root";

    public static void main(String[] args)
    {

        JDBCInsertRecord jdbcInsertRecord = new JDBCInsertRecord();
        jdbcInsertRecord.addCityInformation();

    }

    private void addCityInformation()
    {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try
        {
            /*
             * Register the JDBC driver in DriverManager
             */

            Class.forName(JDBC_DRIVER);

            /*
             * Establish connection to the Database using DriverManager
             */

            connection = DriverManager
                    .getConnection(DB_URL, USERNAME, PASSWORD);

            String sql = "insert into city values  (?,?,?,?,?);";

            /*
             * Execute the query
             */
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 5000);
            preparedStatement.setString(2, "Bangalore");
            preparedStatement.setString(3, "IND");
            preparedStatement.setString(4, "Karnataka");
            preparedStatement.setInt(5, 20000);

            int numberOfRowsInerted = preparedStatement.executeUpdate();

            System.out.println("numberOfRowsInerted : " + numberOfRowsInerted);

            System.out.println("5000th row has been inserted in city table");

        }
        catch (SQLException se)
        {
            /*
             * Handle errors for JDBC
             */
            se.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            /*
             * Handle errors for Class.forName
             */
            e.printStackTrace();
        }

        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if (preparedStatement != null)
                {
                    preparedStatement.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
            try
            {
                if (connection != null)
                {
                    connection.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
        }

    }
}

Output
numberOfRowsInerted : 1
5000th row has been inserted in city table

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCInsertRecordDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCInsertRecordDemoApp.rar?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials