JDBC学习笔记(五)—— 批量处理数据

05、批量插入

5.1、批量执行SQL语句

当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。

JDBC的批量处理语句包括下面三个方法:

  • addBatch(String):添加需要批量处理的SQL语句或是参数;
  • executeBatch():执行批量处理语句;
  • clearBatch():清空缓存的数据。

通常我们会遇到两种批量执行SQL语句的情况:

  • 多条SQL语句的批量处理;
  • 一个SQL语句的批量传参;

5.2、高效的批量插入

题目:向goods表中插入20000条数据

  • 数据库提供一个goods表。创建如下:
CREATE TABLE goods(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(25)
);

5.2.1、实现一:使用Statement

//方式一:使用Statement
Connection con = JDBCUtil.getConnection();
Statement sm = con.createStatement();
for(int i = 1; i <= 20000; i++) {
    String sql = "insert into goods(name) values ('name_ "+ i +"')";
    sm.execute(sql);
}

5.2.2、实现二:使用PreparedStatement

/**
 * 使用PreparedStatement实现批量数据的操作
 *
 * update、delete本身就具有批量操作的效果
 * 此时的批量操作,主要是指批量插入,使用PreparedStatement如何实现更高效的批量插入?
 */
public class InsertTest {
    //批量插入的方式二,使用PreparedStatement
    @Test
    public  void testInsert() {
        Connection con = null;
        PreparedStatement psm = null;

        try {

            con = JDBCUtil.getConnection();
            long start = System.currentTimeMillis();
            String sql = "insert into goods(name) values (?)";
            psm = con.prepareStatement(sql);
            for (int i = 1; i <= 20000; i++) {
                psm.setObject(1, "name_"+i);
                psm.execute();
            }

            long end = System.currentTimeMillis();
            System.out.println("花费的时间:" + (end - start));//花费的时间:23294
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeResource(con, psm);
        }
    }
}

5.2.3、实现三

  • 清空数据库

    TRUNCATE TABLE goods;
    
  • 使用驱动:mysql-connector-java-5.1.37-bin.jar

    项目名 --> 右击,选择Open Module Settings --> 选择Project Settings下的Libraries

在这里插入图片描述

  • 使用batch的相关方法

    package jdbcTest.blob;
    
    import jdbcTest.JDBCUtil;
    import org.junit.Test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    
    public class InsertTest {
        /**
         * 批量插入的方式三:
         * 1.addBatch()、executeBatch()、clearBatch()
         * 2.mysql服务器默认是关闭批处理的,我们需要通过一个参数,让mysql开启批处理的支持。
         *   ?rewriteBatchedStatements=true 写在配置文件的url后面
         * 3.使用更新的mysql 驱动:mysql-connector-java-5.1.37-bin.jar
         
         */
    
        @Test
        public  void testInsert3() {
            Connection con = null;
            PreparedStatement psm = null;
    
            try {
    
                con = JDBCUtil.getConnection();
                long start = System.currentTimeMillis();
                String sql = "insert into goods(name) values (?)";
                psm = con.prepareStatement(sql);
                for (int i = 1; i <= 20000; i++) {
                    psm.setObject(1, "name_"+i);
    
                    //1."攒sql"
                    psm.addBatch();
    
                    if (i % 500 == 0) {
                        //2.执行batch
                        psm.executeBatch();
    
                        //3.清空batch
                        psm.clearBatch();
                    }
                }
    
                long end = System.currentTimeMillis();
                System.out.println("花费的时间:" + (end - start));//20000花费的时间:248
                //1000000话费的时间:5421
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.closeResource(con, psm);
            }
        }
    }
    

5.2.4、实现四

package jdbcTest.blob;

import jdbcTest.JDBCUtil;
import org.junit.Test;

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

public class InsertTest {
    /**
     * 批量插入的方式四:
     */

    @Test
    public  void testInsert4() {
        Connection con = null;
        PreparedStatement psm = null;

        try {

            long start = System.currentTimeMillis();
            con = JDBCUtil.getConnection();

            //设置不允许自动提交数据
            con.setAutoCommit(false);


            String sql = "insert into goods(name) values (?)";
            psm = con.prepareStatement(sql);
            for (int i = 1; i <= 1000000; i++) {
                psm.setObject(1, "name_"+i);

                //1."攒sql"
                psm.addBatch();

                if (i % 500 == 0) {
                    //2.执行batch
                    psm.executeBatch();

                    //3.清空batch
                    psm.clearBatch();
                }
            }

            //提交数据
            con.commit();

            long end = System.currentTimeMillis();
            System.out.println("花费的时间:" + (end - start));//花费的时间:2820
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeResource(con, psm);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,JDBC是Java Database Connectivity的缩写,它是Java语言中用于操作数据库的标准API。在Java程序中使用JDBC查询数据的步骤如下: 1. 加载JDBC驱动程序 在使用JDBC操作数据库之前,需要先加载JDBC驱动程序。可以通过Class.forName()方法来加载驱动程序,例如: ``` Class.forName("com.mysql.jdbc.Driver"); ``` 2. 建立数据库连接 使用DriverManager.getConnection()方法建立与数据库的连接,需要指定数据库的URL、用户名和密码,例如: ``` String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "123456"; Connection conn = DriverManager.getConnection(url, username, password); ``` 3. 创建Statement对象 使用Connection对象的createStatement()方法创建Statement对象,用于执行SQL语句,例如: ``` Statement stmt = conn.createStatement(); ``` 4. 执行SQL语句 使用Statement对象的executeQuery()方法执行查询语句,例如: ``` String sql = "select * from student where age > 18"; ResultSet rs = stmt.executeQuery(sql); ``` 5. 处理查询结果 使用ResultSet对象处理查询结果,例如: ``` while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("id=" + id + ", name=" + name + ", age=" + age); } ``` 6. 关闭资源 使用完ResultSet、Statement和Connection等资源后需要关闭,例如: ``` rs.close(); stmt.close(); conn.close(); ``` 以上就是使用JDBC查询数据的步骤,希望能对你有所帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值