我正在使用执行多个查询的函数。我想让它更快,并且在单个连接后不再打开连接。
我正在使用 sql2o 库将我的 java 程序与 postgresql 连接起来。 ConnectionClass基于Singleton模式。
在此代码中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();
}
最佳答案
您尝试过批处理吗? 看例子here
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.
}
}
关于java - 使用 sql2o 在关闭连接之前执行更多查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57724415/