given dd with a table

create table entry (field Long) 

after connecting to the database you need to generate data in the database from 1 to say 1,000,000

 for (int i = 0; i < n; i++) { try (PreparedStatement st = conn.prepareStatement("INSERT INTO entry VALUES (?)")) { st.setInt(1, 1 + i); st.executeUpdate(); 

and this generation works very slowly; I added the line System.out.println (i); and watch for a long time in the console 4103 4104 4105 4106 4107

while writing the question came only here can you somehow speed up the process?

    1 answer 1

    There are several ways to solve this problem.

    1. Start a transaction before the cycle and commit after

       conn.setAutoCommit(false); for (int i = 0; i < n; i++) { ... } conn.commit(); 
    2. Use batch operations

       try (PreparedStatement st = conn.prepareStatement("INSERT INTO entry VALUES (?)")) { for (int i = 0; i < n; i++) { st.setInt(1, 1 + i); st.addBatch(); } st.executeBatch(); } 
    3. Generate data not in java-code, but by SQL-query

       insert into entry select * from generate_series(0, 1000000, 1);