当前位置: 代码迷 >> J2SE >> 测试setAutoCommit(false)跟executeBatch()发现setAutoCommit(false)没起作用!
  详细解决方案

测试setAutoCommit(false)跟executeBatch()发现setAutoCommit(false)没起作用!

热度:24   发布时间:2016-04-23 22:01:28.0
测试setAutoCommit(false)和executeBatch()发现setAutoCommit(false)没起作用!?
代码:
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost/zhonghongfa?"
+ "user=root&password=841017");

conn.setAutoCommit(false);

pstmt = conn.createStatement();

pstmt.addBatch("insert into ddltable(id,name) values(301,'zhang')");
pstmt.addBatch("insert into ddltable(id,name) values(302,'zhsdfg')");

pstmt.executeBatch();

conn.rollback();


} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
try {
if(conn!=null)
{
conn.rollback();
conn.setAutoCommit(true);
}
} catch (SQLException e) {
e.printStackTrace();
}

}

代码中没有价conn.commit();甚至还进行回滚conn.rollback();但是看数据库,数据却都是插入了!
为什么会这样?

------解决方案--------------------
和setAutoCommit(false)起不起作用么有任何关系。

mysql数据库在创建时需要指定事务类型。并不是所有mysql数据库都是2阶段提交。

------解决方案--------------------
你用的存储引擎支持事务吗?
------解决方案--------------------
http://hi.baidu.com/piaochen/item/96730da849a69f706cd455ff
  相关解决方案