在Java中,PreparedStatement如何处理以下查询
我有一个如下所示的查询,想知道通过批处理PreparedStatement 会生成什么样的SQL。
INSERT INTO table1 (id, version, data)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
table1.data = IF(table1.version > table2.version, table1.data, table2.data),
table1.version = IF(table1.version > table2.version, table1.version, table2.version)
问题是,它会将其解析为批处理中每一行的整个 sql 字符串的副本,还是会执行以下操作:
INSERT INTO table1 (id, version, data)
VALUES (a1, b1, c1), (a2, b2, c2), (a3, b3, c3), ...
ON DUPLICATE KEY UPDATE
table1.data = IF(table1.version > table2.version, table1.data, table2.data),
table1.version = IF(table1.version > table2.version, table1.version, table2.version)
如果不是,性能影响是什么,以及如何以这样的方式编写它:使用PreparedStatement 批处理许多这样的INSERT..UPDATE 语句而不导致性能损失?
I have a query like the following and was wondering what kind of SQL is produced by batching a PreparedStatement.
INSERT INTO table1 (id, version, data)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
table1.data = IF(table1.version > table2.version, table1.data, table2.data),
table1.version = IF(table1.version > table2.version, table1.version, table2.version)
The question is, will it resolve this to a copy of this whole sql string for each row in the batch or will it do something like:
INSERT INTO table1 (id, version, data)
VALUES (a1, b1, c1), (a2, b2, c2), (a3, b3, c3), ...
ON DUPLICATE KEY UPDATE
table1.data = IF(table1.version > table2.version, table1.data, table2.data),
table1.version = IF(table1.version > table2.version, table1.version, table2.version)
If not, what is the performance implication and how do I write it in such a way that I can batch many of these INSERT..UPDATE statements using PreparedStatement without incurring a performance penalty?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
准备好的语句只是将您放入的位置值插入到重复语句中,然后不需要每次都进行解析。因此,您的第二种形式只需要 N * 3 个参数,并且不会为您提供准备好的语句的任何速度改进。对于重复语句,您需要使用 addTobatch。基本上你准备语句,(例如“UPDATE ...???”,然后一次添加3个参数,并一次执行批处理。
我曾经使用这样的东西作为实用程序来包装这个混乱的东西所以你就做类似的事情
A prepared statement just inserts the positional values you put in into a repeating statement which then doesn't need to be parsed each time. So your second form would just require N * 3 parameters and wouldn't give you any of the speed improvement of a prepared statement. For repeating statements you want to use addTobatch. Basically you prepare the statement, (e.g. "UPDATE ... ? ? ? " and then add 3 parameters at a time, and execute the batch all at once.
I used to use something like this as a utility to wrap the messiness of this. So you'd just do something like