jdbc处理事务

public class BankDao extends BaseDao {
	public static void main(String[] args) throws SQLException {
		BankDao bd = new BankDao();
		bd.zz();
	}

	private void zz() throws SQLException {
		// TODO Auto-generated method stub
		Connection conn = super.getConn();
		try {
			conn.setAutoCommit(false);// 设置不可自动提交
			String sql1 = "update zz set user_money=user_money+1000 where user_name='jobs'";
			PreparedStatement ps1 = conn.prepareStatement(sql1);
			int r1 = ps1.executeUpdate();
			String sql2 = "update zz set user_money =user_money-1000 where user_name='bill'";
			PreparedStatement ps2 = conn.prepareStatement(sql2);
			int r2 = ps2.executeUpdate();
			conn.commit();// 提交事务
			System.out.println("yes");
		} catch (Exception e) {
			// 违反约束时,提示错误事务回滚回到执行前
			System.out.println("转账失败!" + e.getMessage());
			conn.rollback();

		}

	}
}
/*
 * sql语句
 * 
 * create table zz( user_id varchar2(10) primary key, user_name varchar2(10) not
 * null, user_money number(10,0) ) alter table zz add constraint
 * check_user_money check(user_money>10) insert into zz values('1','bill',1000);
 * insert into zz values('2','jobs',11); select * from zz
 */


你可能感兴趣的:(Java)