JDBC Batch executing extremely slow

末鹿安然 提交于 2019-12-07 01:42:36

问题


Can anyone tell me what I'm doing wrong I'm executing 350 inserts in a mysql and it's taking like 40 secs.

Here is the code

long t0 = System.currentTimeMillis();
        Connection con = connectionProvider.getConnection();
        PreparedStatement s = con.prepareStatement("insert into domkee.friends(idFriends,friend1Id,friend2Id,friend2Name) values(?,?,?,?)");
        con.setAutoCommit(false);
        for (Friend f : friends) {
            s.setLong(1, 0);
            s.setLong(2, f.getFriend1Id());
            s.setLong(3, f.getFriend2Id());
            s.setString(4, f.getFriend2Name());
            s.addBatch();

        }
        long t1 = System.currentTimeMillis() - t0;
        s.executeBatch();
        long t2 = System.currentTimeMillis()-t0;
        con.commit();
        long t3 = System.currentTimeMillis()-t0;
        s.close();
        con.close();
        long t4 = System.currentTimeMillis()-t0;
        System.out.println(((double)t1/1000) + ";" + ((double)t2/1000) + ";" + ((double)t3/1000) + ";" + ((double)t4/1000));

and here is the console:

0.156;39.251;39.376;39.486

So the .executeBatch() is taking like 40 secs, what could be the problem?


回答1:


Add ?rewriteBatchedStatements=true to the end of your JDBC url. It'll give you a serious performance improvement. Note that this is specific to MySql, won't have any effect with any other JDBC drivers.



来源:https://stackoverflow.com/questions/13504564/jdbc-batch-executing-extremely-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!