事务(ACID)
原子性(atomicity):组成事务处理的语句形成了一个逻辑单元,不能只执行其中的一部分。
一致性(consistency):在事务处理执行前后,数据库是一致的(数据库数据完整性约束)。
隔离性(isolcation):一个事务处理对另一个事务处理的影响。
持续性(durability):事务处理的效果能够被永久保存下来 。
connection.setAutoCommit(false);//打开事务。
connection.commit();//提交事务。
connection.rollback();//回滚事务。
当只想撤销事务中的部分操作时可使用SavePoint
SavePoint sp = connection.setSavepoint();
connection.rollerbak(sp);connection.commit();
package com.us.test;
/*
* 事务处理:需求给id为1的用户增加100元,
* 给id2用户减少100
* 如果id为2的用户钱大于2900,就抛出异常
* */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.us.daoimpl.jdbcUtils;
public class Acidtest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
test();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void test() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = jdbcUtils.getConnection();
//打开事务 为true则会自动提交,一般设置为false
conn.setAutoCommit(false);
String sql = "update userInfo set money =money +100 where id =1";
st = conn.createStatement();
st.executeUpdate(sql);
sql = "select money from userInfo where id =2";
rs = st.executeQuery(sql);
float f =0.0f;
if (rs.next()) {
f =rs.getFloat("money");
}
if (f >2900) {
throw new RuntimeException("已经超过最大值");
}
sql = "update userInfo set money =money -100 where id =2";
st.executeUpdate(sql);
//提交
conn.commit();
} catch (SQLException e) {
if (conn!=null) {
conn.rollback();
throw e;
}
}finally {
jdbcUtils.free(rs, st, conn);
}
}
}
跨数据库事务:(JTA)-----(不同银行转账)
分成两阶段提交。
javax.transaction.UserTransaction tx = (UserTransaction)ctx.lookup(“jndiName");
tx.begin();
//connection1 connection2 (可能来自不同的数据库)…
tx.commit();
//tx.rollback();