JDBC的批量处理语句包括下面四个方法:
方法一:使用Statement实现批量数据的操作
方法二:使用PreparedStatement实现批量数据的操作
方法三:在方法二的基础上添加下面方法
1.addBatch(String):添加需要批量处理的SQL语句或是参数;
2. executeBatch():执行批量处理语句;
3. clearBatch():清空缓存的数据
方法四:在方法三的基础上把默认的自动提交功能关了
//设置不允许自动提交数据
conn.setAutoCommit(false);
//在最后再统一进行提交数据
conn.commit();
package com.atguigu5.blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Test;
import com.atguigu3.util.JDBCUtils;
/*
* 使用PreparedStatement实现批量数据的操作
*
* update、delete本身就具有批量操作的效果。
* 此时的批量操作,主要指的是批量插入。使用PreparedStatement如何实现更高效的批量插入?
*
* 题目:向goods表中插入20000条数据
* CREATE TABLE goods(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(25)
);
* 方式一:使用Statement
* 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);
* }
*
*/
public class InsertTest {
//批量插入的方式二:使用PreparedStatement
@Test
public void testInsert1() {
Connection conn = null;
PreparedStatement ps = null;
try {
long start = System.currentTimeMillis();
conn = JDBCUtils.