java,mysql insert into multiple tables using preparedStatement

自古美人都是妖i 提交于 2019-12-13 22:00:21

问题


Ok, going to reword this question as i made it a bit too complicated before.

i want to take this:

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();

and turn it into something exactly the same, only using:

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

where 'table_name' can be replaced based on what tables[i] is each time through the loop.

i have tried every possible way i can think of so far and all come out the same, either invalid for sql, or simply missing all but the last INSERT each time.

In the end i want to make a loop that will batch up all inserts, perhaps 100, maybe 1000 i dont know. in any case i want it to loop and batch all inserts and then execute the batch once all are made. The other way is to just execute each and every single insert by itself which sorta kills the reason of having the batch function in the first place.

If only there was a way to do this:

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();

however as we all know .setTable does not exist :( if there were then it could be placed into a loop and given a different table value for each pass through the loop. This type of loop will work fine right now provided its all to the same table.


回答1:


Judging by other examples (such as PreparedStatement.addBatch in java has any restrictions?) you can't use just one call to executeBatch when you make multiple calls to prepareStatement. Each call to prepareStatement, although it can have multiple calls to addBatch, must have its own call to executeBatch.

Therefore, to minimize the communication between Java and MySQL, I would consider using a stored procedure in MySQL. And as usual with optimizations, I would try it the simple way before I conclude that the more complex way (the stored procedure) is actually needed.

I also see that other people turn off autocommit when they use executeBatch.



来源:https://stackoverflow.com/questions/11964982/java-mysql-insert-into-multiple-tables-using-preparedstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!