SQL批處理是JDBC性能優化的重要武器,經本人研究總結,批處理的用法有三種。
package lavasoft.jdbctest;
import lavasoft.common.DBToolkit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JDBC的批量操作三種方式
*
* @author leizhimin 2009-12-4 14:42:11
*/
public class BatchExeSQLTest {
public static void main(String[] args) {
exeBatchStaticSQL();
}
/**
* 批量執行預定義模式的SQL
*/
public static void exeBatchParparedSQL() {
Connection conn = null;
try {
conn = DBToolkit.getConnection();
String sql = "insert into testdb.book (kind, name) values (?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "java");
pstmt.setString(2, "jjjj");
pstmt.addBatch(); //添加一次預定義參數
pstmt.setString(1, "ccc");
pstmt.setString(2, "dddd");
pstmt.addBatch(); //再添加一次預定義參數
//批量執行預定義SQL
pstmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection (conn);
}
}
/**
* 批量執行混合模式的SQL、有預定義的,還有靜態的
*/
public static void exeBatchMixedSQL() {
Connection conn = null;
try {
conn = DBToolkit.getConnection();
String sql = "insert into testdb.book (kind, name) values (?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "java");
pstmt.setString(2, "jjjj");
pstmt.addBatch(); // 添加一次預定義參數
pstmt.setString(1, "ccc");
pstmt.setString(2, "dddd");
pstmt.addBatch(); // 再添加一次預定義參數
//添加一次靜態SQL
pstmt.addBatch("update testdb.book set kind = 'JAVA' where kind='java'");
//批量執行預定義SQL
pstmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection (conn);
}
}
/**
* 執行批量靜態的SQL
*/
public static void exeBatchStaticSQL() {
Connection conn = null;
try {
conn = DBToolkit.getConnection();
Statement stmt = conn.createStatement();
//連續添加多條靜態SQL
stmt.addBatch("insert into testdb.book (kind, name) values ('java', 'java in aciton')");
stmt.addBatch("insert into testdb.book (kind, name) values ('c', 'c in aciton')");
stmt.addBatch("delete from testdb.book where kind ='C#'");
stmt.addBatch("update testdb.book set kind = 'JAVA' where kind='java'");
// stmt.addBatch("select count(*) from testdb.book"); //批量執行不支持 Select語句
//執行批量執行
stmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection (conn);
}
}
}
注意:JDBC的批處理不能加入select語句,否則會拋異常:
java.sql.BatchUpdateException: Can not issue SELECT via executeUpdate().
at com.mysql.jdbc.StatementImpl.executeBatch (StatementImpl.java:1007)
出處:http://lavasoft.blog.51cto.com/62575/238651