private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
@Testpublic void testInsert() throws SQLException{ //1、创建QueryRunner对象 QueryRunner queryRunner = new QueryRunner(dataSource); //2、准备方法参数 String sql ="insert into account values(null,?,?)"; Object[] param = {"fff",1000}; //3、调用方法 queryRunner.update(sql, param);}
@Test public void testUpdate() throws SQLException{ QueryRunner queryRunner = new QueryRunner(dataSource); String sql = "update account set money = ? where name = ?"; Object[] param = {2000,"fff"}; queryRunner.update(sql,param); }
@Testpublic void testDelete() throws SQLException{ QueryRunner queryRunner = new QueryRunner(dataSource); String sql = "delete from account where id = ?"; queryRunner.update(sql,2);}
@Testpublic void testTransfer() throws SQLException{ double money = 100; String outAccount = "aaa"; String inAccount = "bbb"; String sql1 = "update account set money = money - ? where name = ?"; String sql2 = "update account set money = money + ? where name = ?"; QueryRunner queryRunner = new QueryRunner(dataSource); queryRunner.update(sql1,money,outAccount); //产生一个错误 int d = 1 / 0; queryRunner.update(sql2,money,inAccount);}
@Test public void testTransfer() throws SQLException{ double money = 100; String outAccount = "aaa"; String inAccount = "bbb"; String sql1 = "update account set money = money - ? where name = ?"; String sql2 = "update account set money = money + ? where name = ?"; //手动事务管理 QueryRunner queryRunner = new QueryRunner(); Connection conn = JDBCUtils.getConnection(); conn.setAutoCommit(false); try { queryRunner.update(conn,sql1,money,outAccount); //产生一个错误 int d = 1 / 0; queryRunner.update(conn,sql2,money,inAccount); DbUtils.commitAndCloseQuietly(conn); } catch (Exception e) { DbUtils.rollbackAndCloseQuietly(conn); e.printStackTrace(); } }