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

在Eclipse中测试MySQL-JDBC(10)preparestatement批处理(同时执行多条sql语句)

2017-09-08 22:13 633 查看
【需求:在数据库中插入1050条数据】

【声明:数据库使用前面文章的数据库和表,不要删,下面的java中没有建数据库和标的功能】

【其他的配置文件及java文件同前面的】

注意:使用PreparedStatement添加批处理的时候不需要添加sql

如:

Statement批处理:st.addBatch(sql)

而PreparedStatement批处理:st.addBatch()

【 java文件未改变,单元测试方法发生了改变】

package com.flying.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.junit.Test;

public class JdbcBatch {
@Test
public void prepareStatementBatch(){
Connection con = null;
PreparedStatement st = null;
try {
con = JdbcUtils.getConnection();
String sql1 ="use batch_test";
String sql2 = "insert into batch values(null,?,?)";//总结中的语句相同
st = con.prepareStatement(sql2);
st.execute(sql1);
for (int i = 1; i <= 1050; i++) {
st.setString(1, "name"+i);//总结中的参数1
st.setString(2, "abc"+i);//总结中的参数2  随着i的变化而不同
st.addBatch();
if (i%1000==0) {
st.executeBatch();
st.clearBatch();
}
}
st.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcUtils.release(con, st);
}
}
}
【执行结果】查看数据库和表,发现表中添加了1050个数据

【命令解释】

Connection.prepareStatement(sql)方法: 预编译sql语句

PreparedStatement.addBatch(): 增加批处理

PreparedStatement.executeBatch(): 执行批处理命令

PreparedStatement.clearBatch();清除批处理的命令

PrepareStatement批处理的优缺点:

优点:发送的是预编译后的SQL语句,执行效率高。

缺点:只能在SQL语句相同,当参数不同的批处理中使用。【实际中参数可以相同,一般参数相同没有什么意义】

         因此这种批处理的方式经常适用于在同一个表中批量插入或者更新数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: