package five.base;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import five.dao.myException.MyUserException;
import five.utils.UtilsSingle;
public class TxTest {
public static void main(String[] args) {
TxTest xuxl = new TxTest();
try {
xuxl.test(1, 2, 2000);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test( int from, int to, float monney) throws SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
UtilsSingle instance = UtilsSingle.getUtilsSingleInstance();
Connection connection = null;
try {
// 创建连接
connection = instance.getConnection();
// 手动控制事务
connection.setAutoCommit(false);
// 创建语句
String sql = "update user set monny = monny - ? where id = ?";
ps = connection.prepareStatement(sql);
// 向占位符 设置参数
ps.setFloat(1, monney);
ps.setInt(2, from);
// 执行语句
int updateNum = ps.executeUpdate();
System.out.println("update Row number is" + updateNum);
sql = "select monny from user where id = ?";
ps = connection.prepareStatement(sql);
ps.setInt(1, to);
// 执行语句
rs = ps.executeQuery();
float toMooey = 0.0f;
System.out.println("result of Row number is" + rs.getRow());
if (rs.next()) {
toMooey = rs.getFloat("monny");
if (toMooey > 1000.0f) {
// 抛出异常后,事务不提交
throw new RuntimeException("id is " + to
+ " of moy > 1000.0f");
}
}
sql = "update user set monny =monny + ? where id = ?" ;
ps=connection.prepareStatement(sql);
ps.setFloat(1, monney);
ps.setInt(2, to);
ps.executeUpdate();
// 数据库的引擎 (通过 show create table user )
// InnoDB 有的支持事务外键 有的不支持
// 不支持数据库的引擎 CRDU快
connection.commit();
} catch (SQLException e) {
if (connection != null) {
System.out.println("回滚了");
connection.rollback();
}
throw new MyUserException(e.getMessage(), e);
} finally {
instance.free(connection, ps, rs);
}
}
}