JDBC————C3P0和DBUtil

这里只学C3P0

https://www.cnblogs.com/star521/p/9026735.html

配置完XML文件后

        Connection conn = null;
		PreparedStatement ps = null;
		try {
			//1. 创建datasource
			ComboPooledDataSource dataSource = new ComboPooledDataSource();
			//2. 设置连接数据的信息
			dataSource.setDriverClass("com.mysql.jdbc.Driver");
			
			配置代码就不需要了
			//dataSource.setJdbcUrl("jdbc:mysql://localhost/bank");
			//dataSource.setUser("root");
			//dataSource.setPassword("root");
			
			//2. 得到连接对象
			conn = dataSource.getConnection();
			String sql = "insert into account values(null , ? , ?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, "admin");
			ps.setInt(2, 1000);
			
			ps.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.release(conn, ps);
		}

DBUtil(用前导入jar包)

        QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
	
		
		//增加
		queryRunner.update("insert into account values (null , ? , ? )", "aa" ,44);
		
		//删除
		queryRunner.update("delete from account where id = ?", 2);
		
		//更新
		queryRunner.update("update account set money = ? where id = ?", 10000 , 556);

用了可变参数的方法解决参数数量不确定问题,用了getParameterMetaData的方法来确定问号的个数。

查询

1. 直接new接口的匿名实现类


		QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
	

		Account  account =  queryRunner.query("select * from account where id = ?", new ResultSetHandler<Account>(){

			@Override
			public Account handle(ResultSet rs) throws SQLException {
				Account account  =  new Account();
				while(rs.next()){
					String name = rs.getString("name");
					int money = rs.getInt("money");
					
					account.setName(name);
					account.setMoney(money);
				}
				return account;
			}
			 
		 }, 6);
		
		System.out.println(account.toString());

把ResultHandler的handle方法交给用户自己根据不同对象来写 

2. 直接使用框架已经写好的实现类。


	* 查询单个对象

		QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
		//查询单个对象
		Account account = queryRunner.query("select * from account where id = ?", 
				new BeanHandler<Account>(Account.class), 8);
	
	
	* 查询多个对象

		QueryRunner queryRunner = new QueryRunner(new ComboPooledDataSource());
		List<Account> list = queryRunner.query("select * from account ",
				new BeanListHandler<Account>(Account.class));

 

    BeanHandler,  查询到的单个数据封装成一个对象
    BeanListHandler, 查询到的多个数据封装 成一个List<对象>

    ArrayHandler,  查询到的单个数据封装成一个数组
    ArrayListHandler,  查询到的多个数据封装成一个集合 ,集合里面的元素是数组。 
    
    MapHandler,  查询到的单个数据封装成一个map
    MapListHandler,查询到的多个数据封装成一个集合 ,集合里面的元素是map。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值