事务(ACID)特点:
l 原子性(atomicity):组成事务处理的语句形成了一个逻辑单元,不能只执行其中的一部分。
l 一致性(consistency):在事务处理执行前后,数据库是一致的(数据库数据完整性约束)。
l 隔离性(isolcation):一个事务处理对另一个事务处理的影响。
l 持续性(durability):事务处理的效果能够被永久保存下来 。
l connection.setAutoCommit(false);//打开事务。
l connection.commit();//提交事务。
l connection.rollback();//回滚事务。
在JDBC中使用事务:
public class TxTest {
public static void main(String[] args) throws SQLException {
test();
}
static void test() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false);
//事务开始
st = conn.createStatement();
String sql = "update user set money=money-10 where id=1";
st.executeUpdate(sql);
sql = "select money from user where id=2";
rs = st.executeQuery(sql);
float money = 0.0f;
if (rs.next()) {
money = rs.getFloat("money");
}
if (money > 400){
throw new RuntimeException("已经超过最大值!");
}
sql = "update user set money=money+10 where id=2";
st.executeUpdate(sql);
//事务结束,这之间就是事务体
conn.commit();
} catch (SQLException e) {
if (conn != null)
conn.rollback();
throw e;
} finally {
JdbcUtils.free(rs, st, conn);
}
}
}