CREATE TABLE `tb_big_data` ( `count` int(11) DEFAULT NULL, `create_time` datetime DEFAULT NULL, `random` double DEFAULT NULL, `str` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
[mysqld]
net_buffer_length=512k
max_allowed_packet=100M
package hewei.study.demo.mysql; import org.springframework.util.StringUtils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; public class InsertTest { static Connection conn = null; public static void initConn() throws ClassNotFoundException, SQLException { String sql; String url = "jdbc:mysql://localhost:3307/develop?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=UTC"; try { // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来, // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来,下面三种形式都可以 Class.forName("com.mysql.cj.jdbc.Driver");// 动态加载mysql驱动 System.out.println("成功加载MySQL驱动程序"); // 一个Connection代表一个数据库连接 conn = DriverManager.getConnection(url); } catch (Exception e) { e.printStackTrace(); } } public static String randomStr(int size) { //定义一个空字符串 String result = ""; for (int i = 0; i < 6; ++i) { //生成一个97~122之间的int类型整数 int intVal = (int) (Math.random() * 26 + 97); //强制转换(char)intVal 将对应的数值转换为对应的字符 //将字符进行拼接 result = result + (char) intVal; } //输出字符串 return result; } public static void insert() { // 开时时间 Long begin = new Date().getTime(); // sql前缀 String prefix = "INSERT INTO tb_big_data (count, create_time, random,str) VALUES "; try { // 保存sql后缀 StringBuffer suffix = new StringBuffer(); // 设置事务为非自动提交 conn.setAutoCommit(false); // Statement st = conn.createStatement(); // 比起st,pst会更好些 PreparedStatement pst = conn.prepareStatement(""); // 外层循环,总提交事务次数 for (int i = 1; i <= 1; i++) { // 第次提交步长 for (int j = 1; j <= 1000000; j++) { // 构建sql后缀 suffix.append("(" + j * i + ", SYSDATE(), " + i * j * Math.random() + ",'" + randomStr(6) + "'),"); } // 构建完整sql String sql = prefix + suffix.substring(0, suffix.length() - 1); // 添加执行sql pst.addBatch(sql); // 执行操作 pst.executeBatch(); // 提交事务 conn.commit(); // 清空上一次添加的数据 suffix = new StringBuffer(); } // 头等连接 pst.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } // 结束时间 Long end = new Date().getTime(); // 耗时 System.out.println("cast : " + (end - begin) / 1000 + " ms"); } public static void main(String[] args) throws SQLException, ClassNotFoundException { initConn(); insert(); } }
10s插入100万条数据
如果用MyISAM引擎就4s
也就是6分钟插入一亿条数据 。是不是很吊了
参考:
https://blog.csdn.net/u010180815/article/details/79166502