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);
}
}