java.sql.SQLException: Can't call commit when autocommit=true
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:67)
at com.mysql.cj.jdbc.ConnectionImpl.commit(ConnectionImpl.java:794)
at com.yc.util.DbHelper.findMutipl(DbHelper.java:119)
at com.yc.web.servlet.day0429.TestConn.testConn(TestConn.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
...
这是在测试mysql是否连接成功时遇到的问题
上网查了下原因,总的来说就是mysql的自动提交功能要关闭。
commit()的作用是:提交上一次提交或者回滚后的修改的内容,并释放连接中的相关内容。
rollback()的作用是:回滚到上一次提交或者回滚时的内容。
上面两个方法都只能在已禁用自动提交的模式中使用。
因此,关闭mysql自动提交就可以了。
在mysql客户端中:
mysql>select @@autocommit;
查看是否开启了自动提交,如果为1,表明开启了。如果是0,表明关闭。
可以采用下面的方式,进行关闭。
mysql>set autocommit=0`;
当上面方法没成功时,这时候是业务代码出现的问题,
这是我自己的业务层代码,Dbhelper中,设置了自动提交,需要改为false,如下图
把conn.commit();改为
conn.setAutoCommit(false);
再运行一次,ok