java-jdbc快速生成无序数据并插入MySQL

2023-12-18 10:57:53

java-jdbc快速生成无序数据并插入MySQL

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Random;
import java.util.stream.IntStream;

public class Demo {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            connection.setAutoCommit(true);

            Statement statement = connection.createStatement();

            String sql = "DROP TABLE IF EXISTS test.t";
            statement.execute(sql);
            sql = "CREATE TABLE test.t (i INT UNSIGNED NOT NULL ,PRIMARY KEY (i))";
            statement.execute(sql);

            sql = "INSERT INTO test.t values";

            int[] array = IntStream.range(1, 1000001).toArray();

            Random random = new Random();
            for (int i = 0; i < 1000000; i++) {
                int i1 = random.nextInt(1000000);
                int i2 = random.nextInt(1000000);
                int temp = array[i1];
                array[i1] = array[i2];
                array[i2] = temp;
            }


            int p = 0;

            for (int i = 0; i < 1000; i++) {
                StringBuilder builder = new StringBuilder(sql);
                for (int k = 0; k < 1000; k++) {
                    builder.append("(").append(array[p]).append(")");
                    if (k != 999) {
                        builder.append(",");
                    }
                    p++;
                }
                statement.execute(builder.toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

文章来源:https://blog.csdn.net/konmor/article/details/135055613
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。