数据库-事务
2015-08-24 18:28
393 查看
用Connection接口的3个函数:
建表:
View Code
事务代码:
//取消自动提交,开启事务 Connection#setAutoCommit(false); //任务失败,回滚 Connection#rollback(); //提交任务 Connection#commit();
建表:
CREATE TABLE bank( bid INT, bname VARCHAR(12), bmoney DOUBLE ) INSERT INTO bank VALUES(1,'tom',1000) INSERT INTO bank VALUES(2,'CC',1500)
View Code
事务代码:
void transaction() { Connection connection = DBHelper.getConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // 取消自动提交,开启事务 connection.setAutoCommit(false); String sql = "UPDATE bank SET bmoney=bmoney-1000 WHERE bid=?"; preparedStatement = (PreparedStatement) connection .prepareStatement(sql); preparedStatement.setInt(1, 1); int updateLine = 0; updateLine = preparedStatement.executeUpdate(); String checkMoney = "SELECT bmoney from bank where bid=?"; preparedStatement = (PreparedStatement) connection .prepareStatement(checkMoney); preparedStatement.setInt(1, 1); resultSet = preparedStatement.executeQuery(); double money = 0; if (resultSet.next()) { money = resultSet.getDouble("bmoney"); } String getmoney = "UPDATE bank SET bmoney=bmoney+1000 WHERE bid=2"; preparedStatement = (PreparedStatement) connection .prepareStatement(getmoney); int getInt = 0; getInt = preparedStatement.executeUpdate(); // 判断是否满足条件 if (updateLine > 0 && money >= 0 && getInt > 0) { // 提交任务 connection.commit(); } else { try { // 任务失败,回滚 connection.rollback(); System.out.println("余额不足!!"); } catch (SQLException e1) { e1.printStackTrace(); } } } catch (SQLException e) { e.printStackTrace(); try { // 任务失败,回滚 connection.rollback(); System.out.println("转账失败!!"); } catch (SQLException e1) { e1.printStackTrace(); } } DBHelper.closeAll(connection, preparedStatement, resultSet); }
相关文章推荐
- sql语句关键字over的作用及用法
- oracle学习笔记一:用户管理(3)用户口令管理
- 范式的数据库具体解释
- 【数据库】E-R模型
- Mysql实现full join的替换方法
- sql over函数使用
- NoSql-MongoDB+Dos窗口下的增删改
- MS sql 小技巧
- oracle函数trunc的使用
- Redis详细,config配置,win和linux下怎么玩,和mysql数据同步。
- 数据库事务隔离级别
- Redis配置文件config详解
- mysql 通过bin-log恢复数据方法
- Postgresql主备同步流复制及主备切换、IP漂移
- Debian 7 安装postgresql 和 postGis
- 数据库(详细步骤)
- 数据库备份Sql
- Mysql事务提交方式
- oracle数据库tns配置方法详解
- 高可用、开源的Redis缓存集群方案 - 赵士杰的博客 - ITeye技术网站