Monday, November 18, 2024
Google search engine
HomeLanguagesJavaHow to Commit a Query in JDBC?

How to Commit a Query in JDBC?

COMMIT command is used to permanently save any transaction into the database. It is used to end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle Database treats as a single unit. This statement also erases all save points in the transaction and releases transaction locks.

When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these commands are not permanent, until the current session is closed, the changes made by these commands can be rolled back. To avoid that, we use the COMMIT command to mark the changes as permanent.

7 steps to Connect our Java program to MySQL Server using JDBC API

  1. Import the package 
  2. Load and Register the driver 
  3. Create a Connection 
  4. Create a Statement 
  5. Execute the Query 
  6. Process the Results
  7. Close the connection
     

We also need to include MySQL connector in our project.

Syntax of Commit

COMMIT;

SQL Queries used in the SQL server to create the respective DB and Table

Creates a Database

CREATE DATABASE <DataBaseName>; 

Current DataBase

use <DataBaseName>;

Creates a Table in the Current DataBase

CREATE TABLE <TableName> (usn int,, name varchar(20)  ,  place varchar (20) );

Example

Java




// importing the my sql package
import java.sql.*;
 
/* The below code cannot generate the output here, since
 * there is no connection between client and mysql server
 *
 * Before running the project in your device
 * make SQL server connection with your project
 
 * create the respective database/table in sql server
 * in URL write the port number in which your mysql server
 * is running (By default it run in port number 3306)
 */
 
public class GFG {
 
    public static void main(String[] args)
    {
        // Database name
        String databaseName = "student";
 
        // Database URL
        String url
            = "jdbc:mysql://localhost:3306/" + databaseName;
 
        // Database credentials
        String userName = "root";
        String password = "root";
 
        Connection con = null;
        Statement st = null;
        ResultSet res = null;
        String query = "";
 
        try {
 
            // Register the jdbc driver
            Class.forName("com.mysql.jdbc.Driver");
 
            // open a connection to database
            con = DriverManager.getConnection(url, userName,
                                              password);
 
            // set auto commit false
            con.setAutoCommit(false);
 
            // creating statement
            st = con.createStatement();
 
            // first let us try to understand , how DB works
            //  without commit statement
            query
                = "INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )";
 
            // executing query 1 -> adding the above
            // information into the table
            st.executeUpdate(query);
            System.out.println(
                "Inserted row 1 FIRST TIME in the table....");
 
            query
                = "INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )";
            st.executeUpdate(query);
            System.out.println(
                "Inserted row 2 FIRST TIME in the table....");
 
            // lets , print what we have updated in the table
            query = "Select * from Student ; ";
            res = st.executeQuery(query);
 
            System.out.println(
                "printing data (without Rollback && without Commit )....");
 
            while (res.next())
                System.out.print(res.getString("name")
                                 + "   ");
            System.out.println();
 
            // lets try to rollback (undo the things ,till now we did)
            // see what difference it will make in the Database
            con.rollback();
 
            // lets checkout our DB again
            query = "Select * from Student";
            res = st.executeQuery(query);
 
            System.out.println(
                "printing data (with Rollback && without Commit )....");
            boolean empty = true;
 
            while (res.next()) {
                empty = false;
                System.out.print(res.getString("name")
                                 + "  ");
            }
            if (empty) {
                System.out.println("Empty table\n\n");
            }
 
            // Since we haven't committed our transaction ,
            // when we did rollback, everything is gone
            // Now lets ,try with the Commit Statement from
            // beginning
            query
                = "INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )";
            st.executeUpdate(query);
            System.out.println(
                "Inserted row 1  SECOND TIME in the table....");
 
            query
                = "INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )";
            st.executeUpdate(query);
            System.out.println(
                "Inserted row 2  SECOND TIME in the table....");
 
            // now we have committed our transaction
            con.commit();
            System.out.println(
                "committed the transaction successfully....");
 
            // lets rollback  and like previous lets check
            // what will be left in our database
            con.rollback();
            System.out.println("Done Rollback....");
 
            query = "Select * from Student";
            res = st.executeQuery(query);
 
            System.out.println(
                "printing data ( with Commit and then Rollback)....");
 
            while (res.next())
                System.out.print(res.getString("name")
                                 + "   ");
 
            System.out.println("\n");
        }
        catch (ClassNotFoundException e) {
            System.out.println("Driver Error");
            e.printStackTrace();
        }
        catch (SQLException e) {
            System.out.println("Connection Error");
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
 
        try {
 
            // Clean-up environment
            if (con != null)
                con.close();
            if (st != null)
                con.close();
            if (res != null)
                res.close();
        }
        catch (Exception e) {
 
            // Handle errors for JDBC
            System.out.println(e.getMessage());
        }
        finally {
            System.out.println("Thank you .........");
        }
    }
}


Output

Inserted row 1 FIRST TIME in the table....
Inserted row 2 FIRST TIME in the table....
printing data (without Rollback && without Commit )....
Ram   Shyam    
printing data (with Rollback && without Commit )....
Empty table


Inserted row 1  SECOND TIME in the table....
Inserted row 2  SECOND TIME in the table....
committed the transaction successfully....
Done Rollback....
printing data ( with Commit and then Rollback)....
Ram   Shyam    

Thank you .........

RELATED ARTICLES

Most Popular

Recent Comments