我是靠谱客的博主 听话金针菇,最近开发中收集的这篇文章主要介绍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.

最后

以上就是听话金针菇为你收集整理的java prepare mysql,java,mysql使用prepareStatement插入多个表的全部内容,希望文章能够帮你解决java prepare mysql,java,mysql使用prepareStatement插入多个表所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部