jar包名称 来源位置 作用
c3p0-0.9.1.2.jar 数据库连接池
mysql-connector-java-5.0.8-bin.jar mysql 数据库连接
commons-dbutils-1.4.jar apache DbUtils 数据库CURD
commons-beanutils-1.8.3.jar DbUtils
commons-logging-1.1.1.jar DbUtils 日志

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/news</property>
    </default-config>  
</c3p0-config> 

示例代码

public class TestJDBC {
    private QueryRunner queryRunner;
   
   @Before
    public void init() {
        DataSource dataSource = new ComboPooledDataSource();
        queryRunner = new QueryRunner(dataSource);
    }
    
    // 添加
    @Test
    public void insert() throws SQLException {
        String insert = "insert into news_user(password,username,email,usertype)values(?,?,?,?)";
        queryRunner.update(insert, "123456", "jack", "www.jack@16.com", 0);
        System.out.println("添加成功");
    }
    
    // 删除
    @Test
    public void delete() throws SQLException {
        String delete = "delete from news_user where id=?";
        queryRunner.update(delete, "6");
        System.out.println("删除成功");
    }
    
    // 修改
    @Test
    public void update() throws SQLException {
        String update = "update news_user set username=? where id=?";
        queryRunner.update(update, "5555", 6);
        System.out.println("修改成功");
    }
    
    // 查询一个
    @Test
    public void findObject() throws SQLException {
        String selectOne = "select * from news_user where id = ?";
        User user = queryRunner.query(selectOne, new BeanHandler<User>(User.class), 6);
        System.out.println(user.toString());
    }
    
    // 查询多个
    @Test
    public void findList() throws SQLException {
        String select = "select * from news_user";
        List<User> list = queryRunner.query(select, new BeanListHandler<User>(User.class));
        for (User user : list) {
            System.out.println(user.toString());
        }
    }
}