Wednesday, 11 December 2013

jdbc program for BatchUpdate using prepared Statement

//jdbc program for BatchUpdate using prepared Statement
/*BatchUpdate: inserting multiple records in a single program*/

import java.sql.*;
import java.util.*;
import java.io.*;
public class BatchUpdateEx2 {

public static void main(String s[]) throws Exception {

Driver d= (Driver) ( Class.forName(
"com.mysql.jdbc.Driver").newInstance());

Properties p=new Properties ();
p.put("user","root");
p.put("password","admin");

Connection con=d.connect("jdbc:mysql://localhost:3306/test",p);
//st.addBatch("insert into emp(empno,ename,sal,deptno) values(102,'Ashwini',4000,30)");

PreparedStatement ps= con.prepareStatement("insert into emp(empno,ename,sal,deptno) values(?,?,?,?)");

ps.setInt(1,204);
ps.setString(2, "santosh");
ps.setDouble(3,1000);
ps.setInt(4,10);

ps.addBatch();

ps.setInt(1,205);
ps.setString(2, "rakesh");
ps.setDouble(3,3000);
ps.setInt(4,5);

ps.addBatch();

try {
int counts[]= ps.executeBatch();
System.out.println("Batch Executed Successfully");
for (int i=0;i<counts.length;i++){
System.out.println("Number of records effected by statement"+(i+1)+": "+counts[i]);
}//for
}//try
catch(BatchUpdateException e){
System.out.println("Batch terminated with an abnormal condition");

int[] counts=e.getUpdateCounts();
System.out.println("Batch terminated at statement"+ (counts.length+1));

for (int i=0;i<counts.length;i++) {
System.out.println("Number of records effected by the statement"+ (i+1)+": "+counts[i]);
}//for
}//catch
con.close();
}//main
}//class

No comments:

Post a Comment