一致性(consistency):在事务处理执行前后,数据库是一致的(两个账户要么都变,或者都不变)。
隔离性(isolcation):一个事务处理对另一个事务处理没有影响。
持续性(durability):事务处理的效果能够被永久保存下来 。
connection.setAutoCommit(false);//打开事务。
connection.commit();//提交事务。
connection.rollback();//回滚事务。
例子:
public class TxTest {
/**
* @param args
* @throws SQLException
*/
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);//1、打开事务
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
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();//2、提交事务
} catch (SQLException e) {
if (conn != null)
conn.rollback();//3、回滚事务
throw e;
} finally {
JdbcUtils.free(rs, st, conn);
}
}
}
当money大于400时候超过最大值,抛出异常,conn.rollback(); 2条sql都会回滚不会执行。
适用于多条sql必须都执行才有效;