简体   繁体   English

Java中的多个SQL语句(带?allowMultiQueries = true)

[英]Multiple SQL Statements in Java (with ?allowMultiQueries=true)

I have a question. 我有个问题。 I work with a lot of SQL Queries and try to work out the best and fastest solution to handle a lot of queries (about 10'000 SQL-queries). 我使用了很多SQL查询,并尝试找出最好和最快的解决方案来处理大量查询(大约10'000个SQL查询)。 I have figured out 2 ways of doing this and would like to hear your opinion on this. 我已经想出了两种方法,并希望听到你对此的看法。 VERSION1 : loop over prepared statements, VERSION2 : allow multiple queries divided by semicolon (by adding "?allowMultiQueries=true" when connecting to the database). VERSION1 :循环准备语句, VERSION2 :允许多个查询除以分号(通过在连接到数据库时添加“?allowMultiQueries = true”)。

Version2 worked out much faster (3 seconds) wheras Version1 was pretty slow (over 1 minute). 版本2的速度要快得多(3秒),而版本1的速度非常慢(超过1分钟)。 So my question is, are there any downsides (or maybe safety concerns) about allowing multiple prepared statements? 所以我的问题是,是否有任何关于允许多个准备好的陈述的缺点(或者可能是安全问题)?

Heres a short code example. 下面是一个简短的代码示例。 Thx for all help! 感谢所有帮助!

// i want to execute the following 3 SQL queries:
String[] SQL = new String[3];
SQL[0] = "UPDATE tbl1 SET age=22 WHERE id=1;";
SQL[1] = "UPDATE tbl1 SET age=80 WHERE id=2;";
SQL[2] = "UPDATE tbl1 SET age=31 WHERE id=3;";

// VERSION1: loop over prepared statements
int[] age = {22,80,31};
int[] id  = { 1, 2, 3};
Connection conn1 = DriverManager.getConnection("jdbc:mysql://EXAMPLE", "user", "pw");
PreparedStatement stmt1_P = conn1.prepareStatement("UPDATE tbl1 SET age=? WHERE id=?;");
for (int i=0; i<SQL.length; i++) {
    stmt1_P.setInt(1, age[i]);
    stmt1_P.setInt(2, id[i]);
    stmt1_P.executeUpdate();
}               

// VERSION2: multiple queries divided by semicolon
Connection conn2 = DriverManager.getConnection("jdbc:mysql://EXAMPLE?allowMultiQueries=true", "user", "pw");
Statement stmt2 = conn2.createStatement();
StringBuilder s = new StringBuilder();
for (int i=0; i<SQL.length; i++) {
    s.append(SQL[i]);
}
stmt2.executeUpdate(s.toString());  

Concatenating statements is generally a good idea. 连接语句通常是个好主意。 As you've discovered, they generate less network traffic and are faster. 正如您所发现的,它们产生的网络流量更少,速度更快。

I don't see any security concerns to worry about. 我不担心担心任何安全问题。

One suggestion to think about: integrity. 一个值得思考的建议:诚信。 If one of your many concatenated statements fails (for whatever reason) you may have some difficulty figuring out which one failed and which ones succeeded. 如果你的许多连接语句中的一个失败(无论出于何种原因),你可能会遇到一些困难,想知道哪一个失败了,哪些失败了。 If you wrap each bunch of concatenated statements in a transaction, you can use ROLLBACK to restore the state of your database if any statements in your bunch fail. 如果在事务中包装每一串连接语句,则可以使用ROLLBACK来恢复数据库中的任何语句失败时的状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM