假设存在表user
id | money |
---|---|
1 | 100 |
2 | 310 |
现在想如果id=2的money<300 ,则将id=1的money-10,同时将id=2的money+10;将其作为一个事务,同时做成功,或同时不成功。
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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(1);
if(money>300)
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);
}
}
}
当id=2的money>300时抛出异常,回滚事务,money不变。