MyBatis 一次性执行多条sql语句,可能吗?
我想知道是否可以一次性执行多个sql语句。 例如,我想从多个表中删除行的情况,有没有办法可以做类似的事情。
<delete id="delete" parameterType="String">
DELETE FROM DUMMYTABLE_A where X=${value}
DELETE FROM DUMMYTABLE_B where X=${value}
</delete>
i was wondering if it is possible to execute multiple sql statements in 1 go.
For example the scenario that i want to delete rows from multiple tables, is there a way i can do things like..
<delete id="delete" parameterType="String">
DELETE FROM DUMMYTABLE_A where X=${value}
DELETE FROM DUMMYTABLE_B where X=${value}
</delete>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我正在将 myBatis 与 Oracle 一起使用。我猜其他数据库也有类似的东西。实际上,您始终可以在数据库中创建过程,这通常对将来需要支持项目时更好。
I'm using myBatis with Oracle. I guess there is something similar in other DB. Actually you always can create procedures in DB, which usually is better for the future, when you have to support the project.
是的,大多数数据库都允许这样做。通常你必须用一些东西来分隔你的 SQL 语句。在 PostGRES 和 MySQL 中,它是分号 (;)。在 Microsoft SQL Server 中,您应该使用关键字 GO。 [ 2013 年 5 月更新:从 SQL Server 2012 开始,您可以而且应该使用分号来分隔语句。在 SQL Server 2012(即下一个版本及更高版本)之后,这些将是强制性的。现在,在 SQL2012 及更高版本中,使用 GO 已被弃用。 ]
MySQL / PostGRES 示例:
MS-SQL 示例:
更好的数据库(即不是 MySQL)也将支持 BEGIN TRAN / COMMIT TRAN / ROLLBACK TRAN 事务。使用事务,您实际上可以将所有语句批处理为一个原子操作,如果其中一部分失败,则所有三个语句都将回滚。请参阅 http://www.sqlteam.com/article/introduction-to-transactions 了解更多信息关于那些。
不过,很可能您所需要的只是 SQL 语句之间的分号!
Yes, most databases allow this. Usually you have to delimit your SQL statements with something. In PostGRES and MySQL it's a semicolon (;). In Microsoft SQL server you should use the keyword GO. [ May 2013 Update: As of SQL Server 2012, you can and should use semicolons to delimit your statements. After SQL Server 2012 (ie. the next version and beyond) these will be mandatory. Using GO is now the deprecated way to do things in SQL2012 and beyond). ]
MySQL / PostGRES example:
MS-SQL example:
Better databases (ie. not MySQL) will also support transactions with BEGIN TRAN / COMMIT TRAN / ROLLBACK TRAN. Using transactions you can actually batch all the statements into one atomic operation, where if part of it failed, all three would be rolled back. See http://www.sqlteam.com/article/introduction-to-transactions for some more information about those.
Most likely all you need is the semicolons between your SQL statements though!
如果有人遇到类似的错误
您可以通过在驱动程序中允许多个查询来解决此问题。
相同
MySQL allowedMultiQuery=true
对于 mariadb ,它与以下 mybatis 问题中描述的
https://github.com/mybatis/mybatis-3/issues/1497
if anyone got an error like
You can fix this by allowing multi queries in your driver.
For mariadb it would be the same as MySQL
allowMultiQuery=true
described in following mybatis issue
https://github.com/mybatis/mybatis-3/issues/1497
此代码适用于
MSSQL
中的一次性多个Select
:This code works for multiple
Select
in one go inMSSQL
: