您通常应该使用Connection.commit()而不是Connection.setAutoCommit(true)来提交事务,除非您想要使用事务切换到autoCommit的’transaction per statement’模型.
也就是说,在事务中调用Connection.setAutoCommit(true)将提交事务(如果驱动程序符合JDBC 4.1规范的10.1.1节).但是你真的应该这样做,如果你的意思是留在autoCommit之后,因为在连接上启用/禁用autoCommit可能会比连接提交更多的连接开销(例如,因为它需要在事务管理器之间切换,做额外的检查等).
您还应该使用Connection.commit()而不使用本机SQL命令COMMIT.详见连接文档:
Note: When configuring a Connection, JDBC applications should use the appropritate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection’s configuration when there is a JDBC method available.
问题是像commit()和setAutoCommit(boolean)这样的命令可以在后台做更多工作,比如关闭ResultSet以及关闭或重置语句.使用SQL命令COMMIT将绕过此命令并可能使您的驱动程序/连接进入错误状态.