java基础之JDBC四:事务简单示例

/**
* 事务
*/
public class Test {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//直接用上一篇文章内写好的工具类创建conn
conn = JDBCSimpleUtils.getConnection();
String sql1 = "UPDATE users SET psw = ? WHERE uid = ? ;";
String sql2 = "INSERT INTO users VALUES(NULL,?,?);";
//开启事务
conn.setAutoCommit(false);
ps = conn.prepareStatement(sql1);
ps.setString(1, "123");
ps.setInt(2, 1);
int u = ps.executeUpdate();
ps = conn.prepareStatement(sql2);
ps.setString(1, "孙燕姿");
ps.setString(2, "123");
int i = ps.executeUpdate();
if (i > 0 && u > 0) {
conn.commit();
;
System.out.println("ok");
} else {
conn.rollback();
System.out.println("error");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCSimpleUtils.release(conn, ps);
}
}
}
上一篇:QT解析嵌套JSON表达式


下一篇:Collection学习目录