Mysql使用java代码快速插入100W数据

          由于压力测试,您需要在数据库中检索大量数据,但数据库中没有太多数据。因此,对于测试,您必须快速将大量临时数据插入数据库。

         有两种方法可以快速插入大量数据:一种是使用java代码实现; 另一种是使用数据库存储过程。

          首先,你必须有一个数据表,注意数据表的引擎,在构建表时使用MyISAM引擎,MyISAM插入比InnoDB快得多,因为InnoDB的事务支持要好得多,并且在大多数情况下是default使用InnoDB,因此您可以在插入数据后将其修改为InnoDB

CREATE TABLE `tb_data` (
  `id` int(11) DEFAULT NULL,
  `user_name` varchar(100) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `random` double DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

        使用java代码,实际插入100万条数据需要6秒。
代码示例:

package com.test;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
 
public class InsertDataDemo {
    static Connection conn = null;
 
    public static void initConn() throws ClassNotFoundException, SQLException {
 
        String url = "jdbc:mysql://localhost:3306/testdb?"
                + "user=root&password=root&useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=UTC";
 
        try {
            / / Dynamically load mysql driver
            Class.forName("com.mysql.jdbc.Driver");
                         System.out.println("Successfully loaded MySQL driver");
            conn = DriverManager.getConnection(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    public static String randomStr(int size) {
                 / / Define an empty string
        String result = "";
        for (int i = 0; i < size; ++i) {
                         / / Generate an int type integer between 97 ~ 122
            int intVal = (int) (Math.random() * 26 + 97);
                         / / Force conversion (char) intVal Convert the corresponding value to the corresponding character, and splicing the characters
            result = result + (char) intVal;
        }
                 / / Output string
        return result;
    }
 
 
    public static void insert(int insertNum) {
                 // open time
        Long begin = System.currentTimeMillis();
                 System.out.println("Start Inserting Data...");
                 // sql prefix
        String prefix = "INSERT INTO tb_data (id, user_name, create_time, random) VALUES ";
 
        try {
                         // save the sql suffix
            StringBuffer suffix = new StringBuffer();
                         / / Set the transaction to non-automatic commit
            conn.setAutoCommit(false);
            PreparedStatement pst = conn.prepareStatement("");
            for (int i = 1; i <= insertNum; i++) {
                                 / / Build sql suffix
                suffix.append("(" + i +",'"+ randomStr(8)  + "', SYSDATE(), " + i * Math.random() + "),");
            }
                         / / Build a complete sql
            String sql = prefix + suffix.substring(0, suffix.length() - 1);
                         / / Add execution sql
            pst.addBatch(sql);
                         // perform the operation
            pst.executeBatch();
                         // commit the transaction
            conn.commit();
      
                         // close the connection
            pst.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
                 // End Time 
        Long end = System.currentTimeMillis();
                 System.out.println("insert"+insertNum+" data data is completed!");
                 System.out.println("Time-consuming : " + (end - begin) / 1000 + "seconds");
    }
 
 
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
 
        initConn();
        insert(1000000);
 
    }
}
 

控制台输出:

Successfully loaded MySQL driver
 Start inserting data...
 Insert 1000000 data data to complete!
 Time consuming : 6 seconds

注意:

     适当增加mysql的max_allowed_pa​​cket参数值允许系统在客户端到服务器端传递大数据时分配更多扩展内存以进行处理。
修改mysql配置文件:

[mysqld]
net_buffer_length=512k
max_allowed_packet=500M

-- 更改引擎的语句
ALTER TABLE 表名 ENGINE=MyISAM;

-- 更改引擎的语句
ALTER TABLE 表明 ENGINE=InnoDB;
 

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

、小H

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值