[英]Insert performance tuning
当前,我们正在从一个database
中选择数据,并将其插入备份数据库( SQL SERVER
)中。
一次选择,此数据始终包含超过15,000条记录。 我们正在使用Enumeration迭代选定的数据。
我们使用JDBC PreparedStatement
将数据插入为:
Enumeration values = ht.elements(); -- ht is HashTable containing selected data.
while(values.hasMoreElements())
{
pstmt = conn.prepareStatement("insert query");
pstmt.executeUpdate();
}
我不确定这是否是进行快速插入的正确或有效方法。
要插入1万行,大约需要30分钟或更长时间。 有什么有效的方法可以使它更快?
注意 :不使用表上的任何索引。
您可以将所有值插入一个sql命令中:
INSERT INTO Table1 ( Column1, Column2 ) VALUES
( V1, V2 ), ( V3, V4 ), .......
您还可以按500条记录批量插入值,例如,如果查询很大。 远程(使用连接)在每个语句的行上插入根本不是很有效。 另一种解决方案是使用存储过程进行插入。 您只需将值作为参数传递给它。
使用上面的INSERT
命令的方法如下:
Enumeration values = ht.elements(); -- ht is HashTable containing selected data.
int i=0;
String sql="";
while(values.hasMoreElements())
{
sql+="(" + values + ")"; //better use StringBuffer here
i++;
if(i % 500 == 0) {
pstmt = conn.prepareStatement("insert query "+sql);
pstmt.executeUpdate();
sql="";
}
else
sql += " , ";
}
使用批处理插入,但是在几次尝试之后提交,不要尝试一次发送所有10K。 尝试调查以获取最佳大小,这是内存与网络旅行之间的权衡。
Connection connection = new getConnection();
Statement statement = connection.createStatement();
int i = 0;
for (String query : queries) {
statement.addBatch("insert query");
if ((i++ % 500) == 0) {
// Do an execute now and again, don't send too many at once
statement.executeBatch();
}
}
statement.executeBatch();
statement.close();
connection.close();
另外,从您的代码中我不确定您在做什么,而是使用参数化查询而不是将10K插入语句作为文本发送。 就像是:
String q= "INSERT INTO data_table (id) values (?)";
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(q);
for (Data d: data) {
ps.setString(1, d.getId());
ps.addBatch();
}
ps.executeBatch();
ps.close();
connection.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.