java prepare mysql,java,mysql使用prepareStatement插入多个表

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值