使用JDBC连接MySQL数据库--典型案例分析(六)----实现账户转账操作(二)

2015-07-24 11:31:43 · 作者: · 浏览: 8
+to+"'"; //关闭自动提交 con.setAutoCommit(false); //执行SQL语句 stmt.executeUpdate(sql1); stmt.executeUpdate(sql2); //提交 con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { System.out.println("回滚事务异常!"); throw new RuntimeException(e); } System.out.println("数据库访问异常!"); throw new RuntimeException(e); }finally{ try { if(stmt!=null){ stmt.close(); } if(con!=null){ con.close(); } } catch (SQLException e) { System.out.println("释放资源时发生异常!"); } } } }

?

步骤四:测试

在Trans类的main方法中,笤俑transfer方法,代码如下所示:

?

public static void main(String[] args) {
			Trans trans=new Trans();
			trans.transfer("A", "B", 500);
	}
运行Trans类,控制台无输出,表示成功,然后查看Mysql数据库中的account表,会发现A账户的金额减少了500元,B账户的金额增加了500元。

?

运行前:\

运行后:\