How to insert data in table using JDBC in java Program

import java.sql.*;

class InsertPrepared
{
    public static void main(String args[])
    {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");

            PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?)");

            stmt.setInt(1, 101);  // 1 specifies the first parameter in the query
            stmt.setString(2, "Ratan");

            int i = stmt.executeUpdate();
            System.out.println(i + " records inserted");

            con.close();
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
}

Step by Step:

1. Importing Required Classes:

import java.sql.*;

The java.sql package is being imported. Classes like Connection, Statement, PreparedStatement, etc are being used in order to talk to a database.

2. Class Declaration

class InsertPrepared {

In the above class it is this class InsertPrepared that holds the whole program in it.

3. Main Method

public static void main(String args[]) {

The main method is the entry point of the program. The execution of the program starts from this method.

4. Try-Catch Block for Error Handling:

try {

A try-catch block is used to handle exceptions such as SQLExceptions. If an error occurs during database operations, it is caught in the catch block.

5. Loading the Oracle JDBC Driver:

Class.forName(“oracle.jdbc.driver.OracleDriver”);

The Class.forName() method invokes Oracle JDBC driver (oracle.jdbc.driver.OracleDriver). It is required to make a connection with Oracle JDBC.

6. Establishing the Database Connection:

Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”, “system”, “oracle”);

  • DriverManager.getConnection() is used to connect to the Oracle database.
  • The connection string jdbc:oracle:thin:@localhost:1521:xe connects to the database at localhost, using port 1521 and the XE database (Oracle Express Edition).
  • The database credentials used are:

Username: system

Password: oracle

7. Creating a PreparedStatement:

PreparedStatement stmt = con.prepareStatement(“insert into Emp values(?, ?)”); 

  • A  PreparedStatement is created with the SQL query insert into Emp values(?, ?)  where  ?  are placeholders for the values to be inserted. This allows the use of parameters and helps avoid SQL injection.
  • stmt is a  PreparedStatement object that will be used to execute the SQL query.

8. Setting Values for Parameters:

stmt.setInt(1, 101); // 1 specifies the first parameter in the query

stmt.setString(2, “Ratan”);

  • stmt.setInt(1, 101) sets the first parameter (position 1) of the PreparedStatement to the integer 101.
  • stmt.setString(2, “Ratan”) sets the second parameter (position 2) of the PreparedStatement to the string “Ratan”.
  • These values will be inserted into the Emp table.

9. Executing the Update:

int i = stmt.executeUpdate();

  • stmt.executeUpdate() executes the SQL query (insert operation) and returns the number of rows affected by the query.
  • Since we are inserting a single record, i will be 1 if the insertion is successful.

10. Print Number of Records Inserted:

System.out.println(i + ” records inserted”);

It is a statement that prints the number of records inserted. As it requires one record, it will print 1 record inserted.

11. Close the Connection:

con.close();

The resources used by the connection are released after the completion of the database operation with the help of con.close().

12. Handling Exceptions:

catch (Exception e) {

       System.out.println(e);

 }

If any exceptions occur (e.g., SQLException), they are caught in the catch block, and the exception message is printed.

Summary of the Process:

1. The Oracle JDBC driver is loaded.

2. A connection to the Oracle database is established using the credentials provided.

3. A PreparedStatement object is created to execute the INSERT query.

4. The values 101 and “Ratan” are set for the placeholders in the query.

5. The query is executed, which inserts a record into the Emp table.

6. The number of affected rows is printed to the console, which is 1.

7. The database connection is closed.

Example Output:

Suppose the Emp table has two columns, say emp_id and emp_name. Then the output will be as follows:

1 record inserted

This shows that one record with emp_id 101 and emp_name  “Ratan” has been successfully inserted into the Emp table.

Possible Errors/Issues:

1. The SQLException will arise when the Emp table does not exist or there are some problems with your connection (maybe your username/password is wrong or database has gone down).

2. Driver Not Found: In case the Oracle JDBC driver was not properly included in your classpath, it will throw a ClassNotFoundException.

Improvements:

1. Use of finally Block: The final block could be added to guarantee the successful closing of the database connection even after an exception.

2. Parameterized Query: The current program uses a parameterized query, which will be safer and more efficient when inserting data.

Leave a Comment

Your email address will not be published. Required fields are marked *