2

我正在使用执行多个查询的函数。我想让它更快,并且在单个之后不要打开连接。

我正在使用 sql2o 库将我的 java 程序与 postgresql 连接起来。ConnectionClass 基于单例模式。

在此代码中,connecton.open() 函数是执行查询时间的调用次数。

public class ConnectionClass{

        private static final ConnectionClass db = new ConnectionClass();
        private final Sql2o sql2o;
        private Connection connection;

private InfraTramDAO() {
        sql2o = new Sql2o("jdbc:postgresql:...............");
    }

private List<Map<String, Object>> queryToList(String query) {

        List<Map<String, Object>> returnList = connection.createQuery(complexSql).executeAndFetchTable().asList();

        return returnList;
    }
}

public void makeObject(FileMapper fileMapper ) {
        ConnectionClass db = ConnectionClass.getInstance();
        db.setConnection(db.getSql2o().open());
        universalCreator(fileMapper );      //function execute few queries
        db.getConnection().close();

    }
4

1 回答 1

1

你试过批处理吗?看这里的例子

public void insertABunchOfRows(){
    final String sql = "INSERT INTO SomeTable(id, value) VALUES (:id, :value)";

    try (Connection con = sql2o.beginTransaction()) {
        Query query = con.createQuery(sql);

        for (int i = 0; i < 100; i++){
            query.addParameter("id", i).addParameter("value", "foo" + i)
                    .addToBatch();
        }

        query.executeBatch(); // executes entire batch
        con.commit();         // remember to call commit(), else sql2o will automatically rollback.
    }
}
于 2019-09-18T12:16:19.903 回答