一步一步学后台(三):C3P0+DBUtils简化代码

2019-03-18  本文已影响0人  itfitness

目录

目录

准备

C3P0:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
   <!--默认配置-->
    <default-config>  
        <property name="initialPoolSize">10</property>  
        <property name="maxIdleTime">30</property>  
        <property name="maxPoolSize">100</property>  
        <property name="minPoolSize">10</property>  
        <property name="maxStatements">200</property>  
    </default-config>  
  
   <!--配置连接池mysql-->
    <named-config name="mysql">  
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>  
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbctest?useSSL=false</property>  
        <property name="user">root</property>  
        <property name="password">123</property>  
        <property name="initialPoolSize">10</property>  
        <property name="maxIdleTime">30</property>  
        <property name="maxPoolSize">100</property>  
        <property name="minPoolSize">10</property>  
        <property name="maxStatements">200</property>  
    </named-config>  
</c3p0-config>

DBUtils:

编写工具类

这里简单的写一个工具类

public class JDBCUtil {
    private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("mysql");//这里的mysql是与c3p0配置文件里相对应的
    public static DataSource getDataSource(){
        return comboPooledDataSource;
    }
}

获取数据库数据

  1. 新建一个Bean类People(后面利用DBUtils可以将结果转为Bean类)
    这里需要与数据库的字段对应。


public class People {
    private int id;
    private String name;
    private String sex;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}
  1. 利用DBUtils的QueryRunner查询数据
public class JDBCTest {
    @Test
    public void Test() throws SQLException{
        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        String sql = "select * from people where sex=? and age>?";//这里使用占位符
        List<People> query = queryRunner.query(sql, new BeanListHandler<>(People.class), "男",16);//这里的查询参数可以有多个,但顺序要对应
        for(People p:query){
            System.out.println(p.getName()+"==");
        }
    }
}
  1. 结果展示


上一篇下一篇

猜你喜欢

热点阅读