JDBC 批处理
批处理允许通过调用 addBatch() 方法将相关的 SQL 语句组合成一个批处理单元,并通过单次调用 executeBatch() 方法提交这些语句。使用 executeBatch() 方法发送多个 SQL 语句可提高性能,因为这样能减少通信开销。可以调用 clearBatch() 方法来清除之前添加到批处理单元中的所有语句。
考虑以下类 Batch,它具有构造函数以及定义表 Record 的方法 createTable() :
public class Batch
{
static final int nRecords = 5;
Connection con;
public Batch(String url) throws ClassNotFoundException, SQLException
{
String user = null;
String password = null;
// Load the driver
Class.forName("com.mcobject.jdbc.McoDriver");
// Connect to the database
con = DriverManager.getConnection(url, user, password);
createTable();
insertBatch(nRecords*3);
// Finally close the database
con.close();
}
public void createTable() throws SQLException
{
Statement stmt = null;
try
{
con.setAutoCommit(true);
String sql = "create table Record(idx int primary key, dec_value int, str_value string)";
stmt = con.createStatement();
stmt.executeUpdate(sql);
stmt.close();
}catch(SQLException e){
e.printStackTrace();
throw e;
}
}
以下方法演示了 addBatch()、clearBatch() 和 executeBatch() 的用法:
public void insertBatch(int initial_idx) throws SQLException {
Statement stmt = null;
try
{
stmt = con.createStatement();
int next_to_last_idx = initial_idx + nRecords;
for (int n=0; n < 3; n++)
{
for (int i=initial_idx; i<next_to_last_idx; i++)
{
String sql = "insert into Record values(" + i +
"," + (100+i) + ",'Str200" + i + "')";
stmt.addBatch(sql);
}
if (n == 2)
{
stmt.clearBatch();
}
int[] res = stmt.executeBatch();
if (n == 2)
{
if (res.length != 0)
{
throw new SQLException("Unexpected : result (" +
res.length + " instead of 0)!");
}
} else {
if (res.length != nRecords)
{
throw new SQLException("Unexpected : result (" +
res.length + " instead of " + nRecords + ")!");
}
for (int j = 0; j < res.length; j++)
{
if (res[j] != 1)
{
throw new SQLException("Unexpected : result [" +
j + "] (" + res[j] + " instead of 1)!");
}
}
}
initial_idx += nRecords;
next_to_last_idx += nRecords;
}
stmt.close();
con.commit();
}catch(SQLException e){
e.printStackTrace();
throw e;
}
}
显然,要执行这些方法,必须在类似下面的主函数中创建一个 Batch 实例:
public static void main(String[] args) throws Exception
{
new Batch("jdbc:smartedb:localhost:5001");
}
示例
在目录 samples/jdbc/JDBCBatch 中的控制台窗口中运行:
../../../target/bin/xsql -i -c xsql.cfg
然后在第二个控制台窗口中运行:
在 Unix/Linux 系统上:
JDBCBatch.sh
在 WIndows 系统上:
JDBCBatch.bat