gpt4 book ai didi

Java JDBC - 使用合并排序进行批量插入的准备语句

转载 作者:行者123 更新时间:2023-12-01 15:03:59 28 4
gpt4 key购买 nike

我正在使用 JDBC 准备好的语句进行批量插入。我正在调用 ps.execute() 方法。如果失败,那么我将调用一个方法,在其中传递参数列表和准备好的语句。我正在使用合并排序技术来划分列表,然后尝试插入记录,但没有成功。

这是我的代码;

来 self 正在调用的executePrepareStatement方法

this.executeInsertStatement(query, myCollection, 0, myCollection.size());

//executeInsertStatement方法

public void executeInsertStatement1(String query, List myCollection, int sIndx, int eIndx) throws DBException,SQLException {

int startIndx = sIndx, endIndx = eIndx, mid = 0;

try {
try{
if(conn.isClosed())
new DataService(CoreConstants.TARGET);
} catch (Exception e) { }
if(startIndx >= endIndx) {
return;
}
conn.setAutoCommit(false);
if (query != null) {
mid = (startIndx + endIndx) / 2;
ps = conn.prepareStatement(query);
executeInsertStatement(query, myCollection, startIndx, mid);
executeInsertStatement(query, myCollection, mid+1, endIndx);
//int end_low = mid;
//int start_high = mid + 1;
if(mid < endIndx)
endIndx = mid;
for (int i = 0; i < endIndx; i++) {
List list = (List) myCollection.get(i);
int count = 1;
for (int j = 0; j < list.size(); j++) {
if(list.get(j) instanceof Timestamp) {
ps.setTimestamp(count, (Timestamp) list.get(j));
} else if(list.get(j) instanceof java.lang.Character) {
ps.setString(count, String.valueOf(list.get(j)));
}
else {
ps.setObject(count, list.get(j));
}
count++;
}
try {
ps.execute();
} catch (Exception e) {
rollback();
}
}
}
} catch (Exception e) {
rollback();
} finally{
try {
if (ps != null) {
ps.close();
ps = null;
}
} catch (Exception ex) {
}
}
}

谢谢

最佳答案

我不认为您使用合并排序走在正确的轨道上。我知道您正在尝试使用分而治之的概念来实现解决方案,但我认为您使问题变得比实际需要的更困难(并且更加困惑/复杂)。

如果我理解正确的话,您已经获得了一个想要插入到数据库中的数据集。而且你会想批量进行。 ReadyStatement 让您可以通过使用几个巧妙的方法来做到这一点:addBatch()executeBatch()

以下概述了我将如何尝试实现您的要求:

  • 我会设置批处理限制,即当我想要执行批处理时批处理中的语句数量。除非我达到这个限制(我可以通过使用计数器很好地跟踪),我将继续添加到批处理

  • 一旦达到限制,我就会执行批处理、重置计数器、清除批处理并重做步骤 #1

  • 这将继续,直到我完成整个数据集。最后,我将根据我的要求将数据提交到数据库,甚至执行回滚。

Have a look at this answer有关如何着手和实现此操作的示例。

关于Java JDBC - 使用合并排序进行批量插入的准备语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13226672/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com