In this example, you can learn about jdbc batch process with prepare statement.
In this example, you can learn about jdbc batch process with prepare statement.In this example, you can learn about jdbc batch process with prepare statement.
First of all, we will create a java class BatchProcessWithPrepareStatement.java class that import java.sql package and after that we will create database connection with this class by using database driver, database url, database name, database username and password as:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://lacalhost:3306/";
String dbname = "roseindia_jdbc_tutorials";
String dbuser =
"root";
String dbpassword =
"root";
Connection conn = null;
Class.forName(driver);
conn = DriverManager.getConnection(url+dbname,dbuser,dbpassword);
Now we will create a prepare statement object as:
PreparedStatement stmt = null;
Now we will create sql insert prepare statement and connect with this statement to prepare statement as:
String insertsql =
"INSERT INTO user(user_id, user_name) "
+
"VALUES(?, ?)";
stmt = conn.prepareStatement(insertsql);
conn.setAutoCommit(false);
stmt.setInt( 1, 50);
stmt.setString( 2, "Deepak"
);
Now we will execute this statement and commit the connection.
The code of the example is:
import java.sql.*; public class BatchProcessWithPrepareStatement { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/"; String dbname = "roseindia_jdbc_tutorials"; String dbuser = "root"; String dbpassword = "root"; Connection conn = null; PreparedStatement stmt = null; try{ Class.forName(driver); conn = DriverManager.getConnection(url+dbname,dbuser,dbpassword); String insertsql = "INSERT INTO user(user_id, user_name) " + "VALUES(?, ?)"; stmt = conn.prepareStatement(insertsql); conn.setAutoCommit(false); stmt.setInt( 1, 50); stmt.setString( 2, "Deepak" ); stmt.addBatch(); stmt.setInt( 1, 51); stmt.setString( 2, "Raj" ); stmt.addBatch(); int[] count = stmt.executeBatch(); System.out.println("Number of effected rows :" + count.length); conn.commit(); stmt.close(); conn.close(); }catch(SQLException se){ se.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } finally{ try{ if(stmt!=null) stmt.close(); } catch(SQLException se2){ } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } } |
Now we will run this example using eclipse IDE and see the output.
Program output:
The eclipse console output is:
The database table output is: