使用JDBC进行批处理

7 篇文章 0 订阅


l业务场景:当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
l实现批处理有两种方式,第一种方式:
Statement.addBatch(sql)
l执行批处理SQL语句
executeBatch()方法:执行批处理命令
clearBatch()方法:清除批处理命令



Connectionconn =null;

Statementst =null;

ResultSetrs =null;

try {

conn =JdbcUtil.getConnection();

String sql1 = "insert into user(name,password,email,birthday)

 values('kkk','123','abc@sina.com','1978-08-08')";

String sql2 = "update user set password='123456' where id=3";

st =conn.createStatement();

st.addBatch(sql1); //SQL语句加入到批命令中

st.addBatch(sql2); //SQL语句加入到批命令中

st.executeBatch();

}finally{

 JdbcUtil.free(conn,st,rs);

}



l采用Statement.addBatch(sql)方式实现批处理:
优点:可以向数据库发送多条不同的SQL语句。
缺点:
SQL语句没有预编译。
当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。例如:

 Insert into user(name,password) values(‘aa’,’111’);

 Insert into user(name,password) values(‘bb’,’222’);

 Insert into user(name,password) values(‘cc’,’333’);

 Insert into user(name,password) values(‘dd’,’444’);



l实现批处理的第二种方式:
PreparedStatement.addBatch()

conn =JdbcUtil.getConnection();

Stringsql = "insert into user(name,password,email,birthday) values(?,?,?,?)";

st =conn.prepareStatement(sql);

for(inti=0;i<50000;i++){

st.setString(1, "aaa" + i);

st.setString(2, "123" +i);

st.setString(3, "aaa" + i + "@sina.com");

st.setDate(4,new Date(1980, 10, 10));

st.addBatch();

if(i%1000==0){

st.executeBatch();

st.clearBatch();

}

}

st.executeBatch();

l 采用 PreparedStatement.addBatch () 实现批处理
优点:发送的是预编译后的 SQL 语句,执行效率高。
缺点:只能应用在 SQL 语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。

另外参见:http://blog.csdn.net/liangkang514/article/details/6981957

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用JDBC批处理操作需要以下步骤: 1. 创建一个Connection对象,连接到数据库。 2. 创建一个Statement对象,用于执行SQL语句。 3. 将多个SQL语句添加到批处理中,使用addBatch方法。 4. 执行批处理使用executeBatch方法。 5. 关闭Statement对象和Connection对象。 下面是一个简单的示例代码,展示如何使用JDBC批处理操作: ```java // 创建Connection对象 Connection conn = DriverManager.getConnection(url, username, password); // 创建Statement对象 Statement stmt = conn.createStatement(); // 添加多个SQL语句到批处理中 stmt.addBatch("INSERT INTO users (id, name) VALUES (1, 'Alice')"); stmt.addBatch("INSERT INTO users (id, name) VALUES (2, 'Bob')"); stmt.addBatch("INSERT INTO users (id, name) VALUES (3, 'Charlie')"); // 执行批处理 int[] results = stmt.executeBatch(); // 关闭Statement对象和Connection对象 stmt.close(); conn.close(); ``` 在上面的示例代码中,我们首先创建了一个Connection对象,连接到数据库。然后创建了一个Statement对象,将多个SQL语句添加到批处理中。最后执行批处理使用executeBatch方法。在执行完批处理之后,我们关闭了Statement对象和Connection对象。 需要注意的是,JDBC批处理操作一般适用于需要处理大量数据的情况,对于小批量数据的处理,使用单条SQL语句执行会更加高效。同时,在使用JDBC批处理操作时,需要注意数据库的限制和性能,以确保数据处理的效率和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值