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 driverClass.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 stringString result = "";for (int i = 0; i < size; ++i) {/ / Generate an int type integer between 97 ~ 122int intVal = (int) (Math.random() * 26 + 97);/ / Force conversion (char) intVal Convert the corresponding value to the corresponding character, and splicing the charactersresult = result + (char) intVal;}/ / Output stringreturn result;}public static void insert(int insertNum) {// open timeLong begin = System.currentTimeMillis();System.out.println("Start Inserting Data...");// sql prefixString prefix = "INSERT INTO tb_data (id, user_name, create_time, random) VALUES ";try {// save the sql suffixStringBuffer suffix = new StringBuffer();/ / Set the transaction to non-automatic commitconn.setAutoCommit(false);PreparedStatement pst = conn.prepareStatement("");for (int i = 1; i <= insertNum; i++) {/ / Build sql suffixsuffix.append("(" + i +",'"+ randomStr(8)  + "', SYSDATE(), " + i * Math.random() + "),");}/ / Build a complete sqlString sql = prefix + suffix.substring(0, suffix.length() - 1);/ / Add execution sqlpst.addBatch(sql);// perform the operationpst.executeBatch();// commit the transactionconn.commit();// close the connectionpst.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 driverStart 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;
 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部