对 java.sql.Connection 的commit方法理解问题

xiwang800 2012-08-18 06:21:28
先看代码:
public boolean addUser() {
int count = -1;
boolean autoCommit = true;
Connection conn = DB.getConn();
String sql = "insert into users() values(null, ? ,? ,'会员', ?, now(), now())" ;

PreparedStatement pstmt = DB.prepareStmt(conn, sql, Statement.RETURN_GENERATED_KEYS);
int key;
String sql2 = "insert into userMsg values(?, '', '', '', 0, 0, 0, '', '')";
PreparedStatement pstmt2 = DB.prepareStmt(conn, sql2);
ResultSet rsKey = null;
try {
autoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);

pstmt.setString(1, userName);
pstmt.setString(2, password);
pstmt.setString(3, email);
count = pstmt.executeUpdate();

rsKey = pstmt.getGeneratedKeys();
rsKey.next();
key = rsKey.getInt(1);
pstmt2.setInt(1, key);
count += pstmt2.executeUpdate();

conn.commit();
conn.setAutoCommit(autoCommit);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DB.close(rsKey);
DB.close(pstmt2);
DB.close(pstmt);
DB.close(conn);
}

if(count >= 2) {
return true;
}
return false;
}

我的原意是在用户表里(users)添加好用户的时候就也顺便在用户信息表(userMsg)添加一个用户信息..用户信息表里的userID
是用户表的主键(自动增长),所以就要用getGeneratedKeys()方法得到刚自动生成的key,但是在执行第二条sql语句时出错了(sql2).但是sql1的信息已经插入到了数据库了...

我的问题就是commit()这个方法不是说是同时成功同时失败的吗???
...全文
596 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiwang800 2012-08-18
  • 打赏
  • 举报
回复
不好意思....首先上面的代码是没错的了...事物能正常的自动回滚..

conn.commit();
conn.setAutoCommit(autoCommit);
} catch (SQLException e) {
e.printStackTrace();
} finally {

出现不能回滚的愿意是先前setAutoCommit(autoCommit)位于 catch (SQLException e)里面,经我测试只要
conn.commit();
conn.setAutoCommit(autoCommit);
不同时出现都会出现事物不能自动回滚的问题....
当然在 catch (SQLException e)加入 conn.rollback() 也行..
未来纪元 2012-08-18
  • 打赏
  • 举报
回复
将一个事务放入try{}中,catch的时候conn.rollback();然后要把conn回复现场,用conn.setAutoCommit(autoCommit);
吉他猪 2012-08-18
  • 打赏
  • 举报
回复
对的你在catch里面要conn.rollback();不回滚事务当然会插入数据
liujiboy 2012-08-18
  • 打赏
  • 举报
回复
出错之后,要rollback

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧