Open In App

How to handle Duplicate Key Violations in JDBC?

The JDBC is the Application Programming Interface for Java programming language. In this article, we will learn how to handle duplicate key violations in JDBC by using try and catch block. If we insert new data with an already existing primary key, we get an SQL exception then we need to handle that exception properly. Otherwise, the new data is successfully inserted into the database. Below we have explained this concept with proper examples for both duplicate key violations and successful insertion.

Handle Duplicate key violations in JDBC

To handle duplicate key violations in JDBC. Here, we have used the primary key concept as well as the try-and-catch concept in Java to handle that duplicate key exception.

Below we provide the table meta information for reference.

Table Structure:

In the below table, we have six columns and four fields:

Table Metadata

Table Data:

Data in Table

Java Program to handle Duplicate Key Violations in JDBC

Example 1: Duplicate key Violations

In this example, inside class, we define the error code to handle the duplicate key violations in JDBC. By using this error code, we will provide the handling message to the end users for understanding what the exact problem is.

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

/**
 * This class demonstrates how to insert data into a database table and handle duplicate key violations in JDBC.
 */
public class RetrieveDataExample {

    /** The error code for duplicate key violations. */
    static final int DUPLICATE_KEY_ERROR_CODE = 1062;

    /**
     * The main method to execute the JDBC code.
     *
     * @param args The command-line arguments.
     */
    public static void main(String[] args) {

        try {
            // Load the JDBC driver class
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish database Connection
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/books", "root", "password");

            // Create a statement object
            Statement stmt = con.createStatement();

            // Define the SQL insert statement
            String sql = "INSERT INTO book (id, author, name, price) VALUES (100,'John Doe', 'My Book', 19.99)";

            // Execute the insert operation
            stmt.executeUpdate(sql);

            // Print success message
            System.out.println("Record inserted successfully.");

            // Close the database connection
            con.close();

        } catch (ClassNotFoundException | SQLException e) 
        {
            // Handle exceptions
            if (((SQLException) e).getErrorCode() == DUPLICATE_KEY_ERROR_CODE) {
                // Handle duplicate key violation
                System.out.println("Duplicate key violation detected. Please change the Id Value");
            } else {
                // Print exception message
                System.out.println(e.getMessage());
            }
        }
    }
}

Output:

Below we can refer to the console output.

Console Output

Explanation of the Program:

Here, the error code is 1062 which indicates the error while duplicate key violations is happening.

Example 2: Successful Insertion

/**
 * This class demonstrates how to insert data into a database table and handle duplicate key violations in JDBC.
 */
public class RetrieveDataExample {

    /** The error code for duplicate key violations. */
    static final int DUPLICATE_KEY_ERROR_CODE = 1062;

    /**
     * The main method to execute the JDBC code.
     *
     * @param args The command-line arguments.
     */
    public static void main(String[] args) {

        try {
            // Load the JDBC driver class
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish database Connection
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/books", "root", "password");

            // Create a statement object
            Statement stmt = con.createStatement();

            // Define the SQL insert statement
            String sql = "INSERT INTO book (id, author, name, price) VALUES (400,'Gupta', 'My Book', 29.99)";

            // Execute the insert operation
            stmt.executeUpdate(sql);

            // Print success message
            System.out.println("Record inserted successfully.");

            // Close the database connection
            con.close();

        } catch (ClassNotFoundException | SQLException e) 
        {
            // Handle exceptions
            if (((SQLException) e).getErrorCode() == DUPLICATE_KEY_ERROR_CODE) {
                // Handle duplicate key violation
                System.out.println("Duplicate key violation detected. Please change the Id Value");
            } else {
                // Print exception message
                System.out.println(e.getMessage());
            }
        }
    }
}

Output:

Below we can see the output in console.

Output in Console

Database Table:

Database Table

Explanation of the above Program:

Article Tags :