我有以下数据库:
CREATE TABLE person_bornYear (name, year INT, prob FLOAT);我有一个带有对象(PersonYear)的向量,其中包含person元素: String name、int year、double prob。
我尝试将向量元素逐行插入到数据库中:
private Statement _stat;
private Connection _conn;
private PreparedStatement _prep;
for (PersonYear py : vecToInsert) {
this.set_prep(this.get_conn().prepareStatement("INSERT into person_bornYear values (?, ?, ?);"));
this.get_prep().setString(1, py.get_person());
this.get_prep().setString(2, Integer.toString(py.get_year()));
this.get_prep().setString(3, Double.toString(py.get_accuracy()));
this.get_prep().executeUpdate();
}它需要2-3分钟(向量包含100K个元素)。
有没有人能告诉我一种更快的方法将向量元素插入到数据库中?
提前谢谢。
发布于 2013-03-04 00:40:36
您可以准确地执行一个简单的批处理查询,如下面的示例所示:http://www.mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/
发布于 2013-02-13 20:45:06
两个可以显著提高代码速度的快速方法:
此代码未经测试,请根据需要进行修改:
this.set_prep(this.get_conn().prepareStatement("INSERT into person_bornYear values (?, ?, ?);"));
for (PersonYear py : vecToInsert) {
this.get_prep().setString(1, py.get_person());
this.get_prep().setString(2, Integer.toString(py.get_year()));
this.get_prep().setString(3, Double.toString(py.get_accuracy()));
this.get_prep().addBatch();
}
this.get_prep.executeBatch();发布于 2013-02-13 20:46:41
首先,您要在每次迭代中实例化相同的准备好的语句。相反,如果您在循环之前实例化它,然后重用它,您可能会获得一些速度。
其次,由于您要同时执行一大堆操作,因此可以使用批量插入:Efficient way to do batch INSERTS with JDBC
如下所示:
PreparedStatement stmt = this.get_conn().prepareStatement("...");
for (...) {
...
stmt.addBatch();
stmt.clearParameters();
}
stmt.executeBatch();第三:为什么这么快插入它们如此重要?如果软件不依赖于数据,您可以考虑使用线程。这将允许主应用程序在数据库处理矢量数据时继续运行。
根据您的数据库后端,您还可以拆分向量并将数据并发插入到不同的线程中。如果你的后端有一个合适的MVCC,它会为你节省很多时间。
https://stackoverflow.com/questions/14853759
复制相似问题