Learn How to use delete MySql statement with JDBC Batch processing.
Learn How to use delete MySql statement with JDBC Batch processing.Learn How to use delete MySql statement with JDBC Batch processing.
First of all, we will create a java class BatchDelete.java. In this class we will create database connection as:
Connection connection =
null;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/databasename","username","passsword");
Now we will used sequence of the step for Batch processing for data insertion in the database table.
1. Create Statement object using createStatement() method on the created Connection object as:
Statement stmt = connection.createStatement();
2. set auto commit is false using setAutoCommit() as:
connection.setAutoCommit(false);
3. Create SQL delete statement for save data in the datasource and add these statement in batch using addBatch() method as:
String deletequery1 =
"Delete from user where user_id=1";
stmt.addBatch(deletequery1);
4. Execute the SQL statements using executeBatch() method on created statement object as:
stmt.executeBatch();
5. Last commit the connection using commit() method as:
connection.commit();
The following code snippet show the full process.
import java.sql.*; public class BatchDelete { public static void main(String[] args) { try{ Connection connection = null; Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/databasename","username","password"); try{ // Create statement object Statement stmt = connection.createStatement(); // Set auto-commit to false connection.setAutoCommit(false); // Delete query String deletequery1 = "Delete from user where user_id=1"; stmt.addBatch(deletequery1); // Delete query String deletequery2 = "Delete from user where user_id=3"; stmt.addBatch(deletequery2); stmt.executeBatch(); System.out.println("Batch delete Processing is done successfully." ); // connection commited connection.commit(); } catch (SQLException s){ System.out.println("SQL Exception " + s); } } catch (Exception e){ e.printStackTrace(); } } } |
Now we will run this example with the eclipse IDE and see the output.
Program output:
The database table data before batch execution the output is:
After batch execution the eclipse console output is:
After batch execution the database table output is: