您的位置:首页 > 编程语言 > Java开发

批量处理---提高处理速度

2014-11-18 19:27 225 查看
批量处理JDBC语句提高处理速度。
当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。
通常情况下比单独提交处理更有效率lJDBC的批量处理语句包括下面两个方法:
addBatch(String):添加需要批量处理的SQL语句或是参数;
executeBatch():执行批量处理语句;
通常我们会遇到两种批量执行SQL语句的情况:
用Statement实现批量处理;
用PreparedStatement实现批量处理;
测试:
@Test
public void testStatementBatch() {
Connection conn = null;
Statement stmt = null;
long time = System.currentTimeMillis();
String sql = "";
try {
conn = DBUtil.getCon();
stmt = conn.createStatement();
for (int i = 0; i < 5000; i++) {
sql = "INSERT INTO b_user(id,NAME,PASSWORD,age) VALUES(1,'vincent','123456',1)";
stmt.addBatch(sql);
}
stmt.executeBatch();
System.out.println("mysql Statement batch time="
+ (System.currentTimeMillis() - time));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.close(conn, stmt, null);
}
}
输出结果为:mysql Statement batch time=147716

@Test
public void testPreparedStatementBatch() {
Connection conn = null;
PreparedStatement pstmt = null;
conn = DBUtil.getCon();
String sql = "INSERT INTO b_user(id,NAME,PASSWORD,age) VALUES(?,?,?,?)";
long time = System.currentTimeMillis();
try {
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < 5000; i++) {
pstmt.setInt(1, 1);
pstmt.setString(2, "t");
pstmt.setString(3, "t");
pstmt.setInt(4, 1);
pstmt.addBatch();
if(i%500==0){
//防止内存溢出
pstmt.execuBatch();
pstmt.clearBatch();
}
}
pstmt.executeBatch();
System.out.println("mysql Preparedstatement batch time="
+ (System.currentTimeMillis() - time));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.close(conn, pstmt, null);
}
}
输出结果为:mysql Preparedstatement batch time=152905

@Test
public void testEff() {
Connection conn = null;
PreparedStatement pstmt = null;
long time = System.currentTimeMillis();
conn = DBUtil.getCon();

String sql = "INSERT INTO b_user(id,NAME,PASSWORD,age) VALUES(?,?,?,?)";
try {
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < 5000; i++) {
pstmt.setInt(1, 1);
pstmt.setString(2, "t");
pstmt.setString(3, "t");
pstmt.setInt(4, 1);
pstmt.executeUpdate();
}
System.out.println("no batch:"+(System.currentTimeMillis()-time));
} catch (Exception e) {
}
}
输出结果为:no batch:120776

怎么看着用批量处理比不是用批量处理还慢呢。
如果使用Oracle并结合使用batch,那么效率是成倍增长的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息