java,mysql使用preparedStatement插入多个表

时间:2012-08-15 06:31:18

标签: java mysql insert prepared-statement

好的,我要改编这个问题,因为我之前有点太复杂了。

我想接受这个:

con.setAutoCommit(false);
String tempforbatch;
Statement stmt = con.createStatement();
for (int i = 0; i < tables.length; i++) {
     tempforbatch = "INSERT INTO " + tables[i] + " VALUES ('" + values[i] + "')";
     stmt.addBatch(tempforbatch);
}
stmt.executeBatch();

并将其转换为完全相同的内容,仅使用:

PreparedStatement stmt = con.prepareStatement("INSERT INTO table_name VALUES (?, ?)");

其中'table_name'可以根据每次循环时的表[i]来替换。

我已经尝试了到目前为止我能想到的所有可能的方式,并且都是相同的,对于sql来说无效,或者只是每次都丢失除了最后一次INSERT之外的所有内容。

最后我想制作一个循环,将批量所有插入,也许100,也许1000我不知道。在任何情况下,我希望它循环和批处理所有插入,然后一旦完成所有执行批处理。另一种方法是单独执行每个单独的插入,这有点排除了首先具有批处理功能的原因。

如果只有办法做到这一点:

PreparedStatement stmt = con.prepareStatement("INSERT INTO ? VALUES (?, ?)");
...loop code here....
stmt.setTable(1, "table1");
stmt.setString(2, "value1");
stmt.setString(3, "value2");
stmt.addBatch();
...end loop here....
stmt.executeBatch();
然而,正如我们都知道的那样.setTable不存在:(如果有的话,它可以放入一个循环中,并为每次通过循环赋予不同的表值。这种类型的循环现在可以正常工作所有人都在同一张桌子上。

1 个答案:

答案 0 :(得分:0)

通过其他示例(例如PreparedStatement.addBatch in java has any restrictions?)判断,当您多次调用prepareStatement时,不能只使用一次executeBatch调用。每次调用prepareStatement,虽然它可以多次调用addBatch,但必须有自己的executeBatch调用。

因此,为了最大限度地减少Java和MySQL之间的通信,我会考虑在MySQL中使用存储过程。和往常一样,在我推断实际需要更复杂的方式(存储过程)之前,我会以简单的方式尝试它。

我还看到其他人在使用e​​xecuteBatch时关闭了自动提交。