批量操作
一次可以执行多条sql语句.
在jdbc中可以执行sql语句的对象有Statement,PreparedStatement,它们都提供批处理.
1.Statement执行批处理
addBatch(String sql); 将sql语句添加到批处理
executeBatch(); 执行批处理
clearBatch();
2.PreparedStatement执行批处理
addBatch();
executeBatch();
clearBatch();
以上两个对象执行批处理区别?
1.Statement它更适合执行不同sql的批处理。它没有提供预处理功能,性能比较低。
2.PreparedStatement它适合执行相同sql的批处理,它提供了预处理功能,性能比较高。
注意;mysql默认情况下,批处理中的预处理功能没有开启,需要开启
1.在 url下添加参数
url=jdbc:mysql:///day17?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
2.注意驱动版本
Mysql驱动要使用mysql-connector-java-5.1.13以上
Statement执行批处理
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 批量处理多条sql语句
*
* @author lenovo
*
*/
public class StatementBatchTest {
public static void main(String[] args) throws SQLException {
// 定义Sql语句
String sql1 = "create table person(id int,name varchar(20))";
String sql2 = "insert into person values(1,'tom')";
String sql3 = "insert into person values(2,'fox')";
String sql4 = "insert into person values(3,'tony')";
String sql5 = "update person set name='张三' where id=1";
String sql6 = "delete from person where id=3";
// 获取连接对象
Connection con = JdbcUtils2.getConnection();
// 获取Statement 操作语句
Statement st = con.createStatement();
// 批处理执行SQL
st.addBatch(sql1);
st.addBatch(sql2);
st.addBatch(sql3);
st.addBatch(sql4);
st.addBatch(sql5);
st.addBatch(sql6);
// 批量处理
int[] batch = st.executeBatch();
// 释放资源
JdbcUtils2.closeStatement(st);
JdbcUtils2.closeConnection(con);
}
}
PreparedStatement执行批处理
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 批量处理 需求: 向Person 表中插入100000条数据
*
* @author lenovo
*
*/
public class PreparedStatementTest {
public static void main(String[] args) throws Exception {
// sql语句
String sql = "insert into person values(?,?)";
// 获取连接对象
Connection con = JdbcUtils2.getConnection();
// 获取PrepareStatement对象
PreparedStatement pst = con.prepareStatement(sql);
// 批处理开始时间
long start = System.currentTimeMillis();
for (int i = 1; i <= 100000; i++) {
pst.setInt(1, i);
pst.setString(2, "name" + i);
if (i % 1000 == 0) {
pst.executeBatch();
pst.clearBatch();
}
// 批处理执行
pst.addBatch();
}
JdbcUtils2.closePreparedStatement(pst);
JdbcUtils2.closeConnection(con);
long end = System.currentTimeMillis();
System.out.println("执行的时间为:" + (end - start));
}
}