Mysql的批处理机制

           当我们有多条sql语句需要发送到数据库执行的时候,有两种发送方式,一种是执行一条发送一条sql语句给数据库,另一个种是发送一个sql集合给数据库,也就是发送一个批sql到数据库。很显然两者的数据库执行效率是不同的,我们发送批处理sql的时候数据库执行效率要高。所以我们有必要掌握mysql数据库的sql批处理发送方式方法。以下我在复习JDBC的时候,复习到的sql批处理的方法,希望能够帮助有需要的人。

第一种方式代码如下:

//实现mysql 数据库批处理的第一种方式
@Test
public void test1(){
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = JDBCUtil.getConnection();
String sql = "insert into testbatch(id,name) values('1','aaa')";
String sql2 = "update testbatch set name = 'bbb' where id = '1'";
st=(Statement) connection.createStatement();
st.addBatch(sql);
st.addBatch(sql2);

//[1,4]
st.executeBatch();
st.clearBatch();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(rs, st, connection);
}

}

运行成功后数据库表显示的结果为:1   bbb

第二种方式,代码如下:

//mysql数据库批处理的第二种方式
@Test
public void test2(){
Connection connection = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
connection = JDBCUtil.getConnection();
String sql = "insert into testbatch(id,name) values(?,?)";
st =(PreparedStatement) connection.prepareStatement(sql);
st.setString(1,"1");
st.setString(2,"aa");
st.addBatch();
st.setString(1,"2");
st.setString(2,"bb");
st.addBatch();
st.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(rs, st, connection);
}

}

运行结果如下 


猜你喜欢

转载自blog.csdn.net/lvhaoguang0/article/details/80874536