JDBC: 批量处理提高SQL处理速度

来源:互联网 发布:网络流行文化有哪些 编辑:程序博客网 时间:2024/05/21 23:32
   当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率
JDBC的批量处理语句包括下面两个方法:
addBatch(String):添加需要批量处理的SQL语句或是参数;
executeBatch();执行批量处理语句;
通常我们会遇到两种批量执行SQL语句的情况:
多条SQL语句的批量处理;

一个SQL语句的批量传参;

测试代码:

import java.sql.Connection;import java.sql.Date;import java.sql.PreparedStatement;import java.sql.Statement;import org.junit.Test;import xuezaipiao1.JDBC_Tools;/** * 向Oracle 的 temp 数据表中添加  10万 条记录 * 测试如何插入,用时最短 */public class JDBCTest {/** *  * 1.使用 Statement . * 测试用时:35535 */@Testpublic void testBbatchStatement() {Connection conn = null;Statement statement = null;String sql = null;try {conn = JDBC_Tools.getConnection();JDBC_Tools.beginTx(conn);long beginTime = System.currentTimeMillis();statement = conn.createStatement();for(int i = 0;i<100000;i++){sql = "INSERT INTO temp values("+(i+1)+",'name_"+(i+1)+"','13-6月 -15')";statement.executeUpdate(sql);}long endTime = System.currentTimeMillis();System.out.println("Time : "+(endTime - beginTime));JDBC_Tools.commit(conn);} catch (Exception e) {e.printStackTrace();JDBC_Tools.rollback(conn);}finally{JDBC_Tools.relaseSource(conn, statement);}}/** * 使用PreparedStatement  * 测试用时:9717 */@Testpublic void testBbatchPreparedStatement() {Connection conn = null;PreparedStatement ps = null;String sql = null;try {conn = JDBC_Tools.getConnection();JDBC_Tools.beginTx(conn);long beginTime = System.currentTimeMillis();sql = "INSERT INTO temp values(?,?,?)";ps = conn.prepareStatement(sql);Date date = new Date(new java.util.Date().getTime());for(int i = 0;i<100000;i++){ps.setInt(1, i+1);ps.setString(2, "name_"+i);ps.setDate(3, date);ps.executeUpdate();//9717}long endTime = System.currentTimeMillis();System.out.println("Time : "+(endTime - beginTime));JDBC_Tools.commit(conn);} catch (Exception e) {e.printStackTrace();JDBC_Tools.rollback(conn);}finally{JDBC_Tools.relaseSource(conn, ps);}}/** * 测试用时 : 658 */@Testpublic void testBbatch() {Connection conn = null;PreparedStatement ps = null;String sql = null;try {conn = JDBC_Tools.getConnection();JDBC_Tools.beginTx(conn);long beginTime = System.currentTimeMillis();sql = "INSERT INTO temp values(?,?,?)";ps = conn.prepareStatement(sql);Date date = new Date(new java.util.Date().getTime());for(int i = 0;i<100000;i++){ps.setInt(1, i+1);ps.setString(2, "name_"+i);ps.setDate(3, date);//积攒SQLps.addBatch();//当积攒到一定程度,就执行一次,并且清空记录if((i+1) % 300==0){ps.executeBatch();ps.clearBatch();}}//总条数不是批量值整数倍,则还需要在执行一次if(100000 % 300 != 0){ps.executeBatch();ps.clearBatch();}long endTime = System.currentTimeMillis();System.out.println("Time : "+(endTime - beginTime));JDBC_Tools.commit(conn);} catch (Exception e) {e.printStackTrace();JDBC_Tools.rollback(conn);}finally{JDBC_Tools.relaseSource(conn, ps);}}}



0 0
原创粉丝点击