事物

	//类似于main方法
	@Test
	public void test3() throws SQLException {
		//connection 事物
		Connection conn = null;
		//异常最大化
		try {
			//创建数据库链接
			conn=C3P0Utils.getConnection();
			//关闭事物自动提交
			conn.setAutoCommit(false);
			//sql
			String sql = "update product set price=price+10000 where pid=6";
			//编译sql
			PreparedStatement pr = conn.prepareStatement(sql);
			//执行sql
			int update = pr.executeUpdate();
			System.out.println("更新了"+ update +"次");
			//出现异常最大化,防止转钱时候失误
			int a=1/0;
			//sql
			String sql1 = "update product set price=price-10000 where pid=7";
			//编译sql
			PreparedStatement pr1 = conn.prepareStatement(sql);
			//执行sql
			int update1 = pr.executeUpdate();
			System.out.println(update1);
			//提交事物
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//解决异常
			conn.rollback();
			//必执行finally内容
		}finally {
			//关流
			conn.close();
		}
		//
	}
}

  

posted on 2020-09-28 21:21  爱前端的小魏  阅读(168)  评论(0编辑  收藏  举报

导航