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);
}
}
}