[Reprint] About PreparedStatement. addBatch () method, statementaddbatch
The difference between Statement and PreparedStatement is not nonsense. Let's talk about the use of the most important addbatch () structure of PreparedStatement.
1. Create a link (call dialing)
Connection connection = getConnection ();
2. Do not automatically Commit (melon seeds are not eaten one by one, they are all peeled off and opened on the table, and then licked)
Connection. setAutoCommit (false );
3. Pre-compile the SQL statement and compile it only once. It is highly efficient. (If you create a method to peel the seeds, do not always think about how to peel the seeds in the future. In this way, you can peel them out .)
PreparedStatement = connection. prepareStatement ("insert into tablex values (?, ?) ");
4. Peel one and put it on the table.
// Record 1
Statement. setInt (1, 1 );
Statement. setString (2, "Cujo ");
Statement. addBatch ();
// Record 2
Statement. setInt (1, 2 );
Statement. setString (2, "Fred ");
Statement. addBatch ();
// Record 3
Statement. setInt (1, 3 );
Statement. setString (2, "Mark ");
Statement. addBatch ();
// Execute the preceding three statements in batches. It's nice to swallow it.
Int [] counts = statement.exe cuteBatch ();
// Commit it swallow down to the stomach (DB)
Connection. commit ();
Stmt. addBatch ("update TABLE1 set question =" Summer Session foot care 1 "where id =" 3407 "");
Stmt. addBatch ("update TABLE1 set question =" Summer heatstroke prevention diet 1 "where id =" 3408 "");
Stmt. addBatch ("insert into TABLE1 VALUES (" 11 "," 12 "," 13 ","","")");
Stmt. addBatch ("insert into TABLE1 VALUES (" 12 "," 12 "," 13 ","","")");
Stmt. addBatch ("insert into TABLE1 VALUES (" 13 "," 12 "," 13 ","","")");
Stmt. addBatch ("insert into TABLE1 VALUES (" 14 "," 12 "," 13 ","","")");
Stmt. addBatch ("insert into TABLE1 VALUES (" 15 "," 12 "," 13 ","","")");
Stmt. addBatch ("insert into TABLE1 VALUES (" 16 "," 12 "," 13 ","","")");
Stmt. addBatch ("insert into TABLE1 VALUES (" 17 "," 12 "," 13 ","","")");
Stmt. addBatch ("insert into TABLE1 VALUES (" 18 "," 12 "," 13 ","","")");
Int [] updatecounts1_stmt.exe cuteBatch ();
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.exe cuteBatch ();
};
Link: http://blog.csdn.net/blueling51/article/details/6928755