dbutils概述

dbutils的增删改

package com.dbutils;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.packge.Account;

public class Demo {
	@Test
	public void test() throws SQLException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		//创建
		QueryRunner runner = new QueryRunner(dataSource);
		//增 删 改
		//runner.update("insert into account values (null,?,?)", "aa",123);
		
		//查询:
		//查询得到一个javabean类 需要封装里面的数据
		//去执行查询,查询的数据还是在那个result里面,调用下面的handle方法 由用户去封装account
		Account account = runner.query("select *from account where id = ?",
				//new 这个接口的匿名内部类 实现account类 并实现里面的方法
				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.setMoney(money);
					account.setName(name);
				}
				return account;
			}
			
		} , 10);
		System.out.println(account.toString());
	}
}

dbutils的查

package com.packge;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.runner.Runner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class demo02 {

	public void test() throws SQLException {
	//得到连接

 - ComboPooledDataSource dataSource = new ComboPooledDataSource();
   	QueryRunner runner = new QueryRunner(dataSource); 	 	/* 	查询单个 	 *
   Account account = (Account) 	 * runner.query("select *from account
   where id = ?",new 	 * BeanHandler(Account.class) , 10); 	 *
   System.out.println(account.toString()); 	 */

	
	//查询多个
	List<Account> query = runner.query("select *from where ", new BeanListHandler<Account>(Account.class));
	for (Account account : query) {
		System.out.println(account.toString());
	}
	
	}
}

dbutils概述_第1张图片

你可能感兴趣的:(sql)