合并多条insert

最近更新时间: 2024-10-17 17:10:00

import java.sql.*;
import java.util.Random;
import java.util.UUID;
public class batch {
    public static void main(String args[]) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://172.16.0.30:11345/postgres?reWriteBatchedInserts=true","tbase", "tbase");
            conn.setAutoCommit(true);
            System.out.println("Opened database successfully");
            //开始执行批量插入
            String insert_sql = "INSERT INTO t1 VALUES (?,?)";
            try {
                assert conn != null;
                PreparedStatement preparedStatement = conn.prepareStatement(insert_sql);
                for (int i = 0; i < 100000; i++) {
                    preparedStatement.setInt(1, new Random().nextInt(1000));
                    preparedStatement.setString(2, UUID.randomUUID().toString());
                    preparedStatement.addBatch();
                    if (i % 500 == 0) {
                        preparedStatement.executeBatch();
                        preparedStatement.clearBatch();
                    }
                }
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            System.err.println( e.getClass().getName()+": "+ e.getMessage() );
            System.exit(0);
        }
        System.out.println("Records created successfully");
    }
}