About Preparedstatement Addbatch() method (transfer)
There is not much nonsense about the difference between a statement and a Preparedstatement. Let's directly talk about the use of the most important addbatch () structure of a Preparedstatement
1. Establish a link, (call and dial)
Connection connection =getConnection();
2. No automatic commit (melon seeds are not eaten one by one, all peeled and opened on the table, and then licked)
connection. setAutoCommit(false);
3. Precompile SQL statements and compile them only once. It's efficient (invent a method to peel melon seeds. Don't always think about how to peel melon seeds in the future. Just peel them like this.) PreparedStatement statement = connection. prepareStatement("INSERT INTO TABLEX VALUES(?,?)");
4. Peel one by one and put it on the table
//Record 1 statement setInt(1,1); statement. setString(2,"Cujo"); statement. addBatch();
//Record 2 statement addBatch();
//Record 3 statement addBatch();
//Execute the above three statements in batch Swallow it in one mouthful. Int [] counts = statement executeBatch();
//Commit swallow it and connect it to the belly (DB) commit();
stmt. Addbatch ("update table1 set topic =" midsummer foot care 1 "where id =" 3407 ""); stmt. Addbatch ("update table1 set topic =" summer heatstroke prevention diet 1 "where id =" 3408 ""); stmt. addBatch("INSERT INTO TABLE1 VALUES("11","12","13","","")"); stmt. addBatch("INSERT INTO TABLE1 VALUES("12","")"); stmt. addBatch("INSERT INTO TABLE1 VALUES("13","")"); stmt. addBatch("INSERT INTO TABLE1 VALUES("14","")"); stmt. addBatch("INSERT INTO TABLE1 VALUES("15","")"); stmt. addBatch("INSERT INTO TABLE1 VALUES("16","")"); stmt. addBatch("INSERT INTO TABLE1 VALUES("17","")"); stmt. addBatch("INSERT INTO TABLE1 VALUES("18","")"); int [] updateCounts=stmt. executeBatch(); cn. commit();
For example:
public static void execteBatch(Connection conn)throws Exception{ String sql1 = "delete from student where id =3 "; String sql2 = "delete from student where id =5 "; String sql3 = "delete from student where id =6 "; String sql4 = "delete from student where id =7 "; PreparedStatement pstmt = conn.prepareStatement(sql1); pstmt.addBatch() ; pstmt. addBatch(sql2); pstmt. addBatch(sql3); pstmt. addBatch(sql4); pstmt. executeBatch(); };
This article is transferred from: http://blog.csdn.net/blueling51/article/details/6928755 。