目录
一、批量插入数据
⚪JDBC的批量处理语句的方法
二、高效的批量插入
1.举例:向goods表中插入20000条数据
⭐goods表的创建
方式一:使用Statement
方式二: 使用PreparedStatement替换Statement
方式一与方式二的对比
方式三: 相关方法的调用
方式四: 设置连接不允许自动提交数据
当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处 理。通常情况下比单独提交处理更有效率
CREATE TABLE goods(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(25)
);
public class InsertTest {
//方式一:使用Statement
@Test
public void test1() throws Exception {
Connection conn = JDBCUtils.getConnection();
Statement st = conn.createStatement();
for (int i = 1; i < 20000; i++) {
String sql = "insert into goods (name) values ('name_" + i + "')";
st.execute(sql);
}
}
}
@Test
public void test2() {
Connection conn = null;
PreparedStatement ps = null;
try {
long start = System.currentTimeMillis();
conn = JDBCUtils.getConnection();
String sql = "insert into goods (name) values (?)";
ps = conn.prepareStatement(sql);
for (int i = 1; i <= 20000; i++) {
ps.setObject(1,"name_" + i); //填充占位符
ps.execute();
}
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" +(end - start));
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps);
}
}
PreparedStatement 能最大可能提高性能:
PreparedStatement 可以防止 SQL 注入
@Test
public void test3() {
Connection conn = null;
PreparedStatement ps = null;
try {
long start = System.currentTimeMillis();
conn = JDBCUtils.getConnection();
String sql = "insert into goods (name) values (?)";
ps = conn.prepareStatement(sql);
for (int i = 1; i <= 20000; i++) {
ps.setObject(1, "name_" + i); //填充占位符
//1."攒"sql
ps.addBatch();
if (i % 500 == 0){
//2.执行Batch
ps.executeBatch();
//3.清空Batch
ps.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" + (end - start));
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, ps);
}
}
时间变化:33899 ———> 2243
@Test
public void test4() {
Connection conn = null;
PreparedStatement ps = null;
try {
long start = System.currentTimeMillis();
conn = JDBCUtils.getConnection();
//设置不允许自动提交数据
conn.setAutoCommit(false);
String sql = "insert into goods (name) values (?)";
ps = conn.prepareStatement(sql);
for (int i = 1; i <= 20000; i++) {
ps.setObject(1, "name_" + i); //填充占位符
//1."攒"sql
ps.addBatch();
if (i % 500 == 0){
//2.执行Batch
ps.executeBatch();
//3.清空Batch
ps.clearBatch();
}
}
//统一提交数据
conn.commit();
long end = System.currentTimeMillis();
System.out.println("花费的时间为:" + (end - start));
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, ps);
}
}