DButils配合Spring的IOC

DButils的基本使用

1. 获取QueryRunner对象(相当于JdbcTemplate)
    构造(常用):
        QueryRunner runner = new QueryRunner();
        QueryRunner runner = new QueryRunner(param);
    参数:
        第一个没有参数
        第二个的参数是数据库连接池(可以使用c3p0/druid)
2. 执行sql语句
    增删改:    runner.update(“增删改sql”,参数列表);
    查询:   runner.query(“查询sql”,返回数据,参数列表);

    增:
        runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
    删:
        runner.update("delete from account where id = ? ",account.getId())
    改:
        runner.update("update account set name = ? and money=? where id = ?",account.getName(),account.getMoney()
        ,account.getId())
    查:
        查一个
            runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id)
        查多个
            runner.query("select * from account", new BeanListHandler<Account>(Account.class))
        * 注: 
            一条数据使用BeanHandler
            多条数据使用BeanListHandler

DButils在Spring中IOC的应用

*基于xml的配置:(构造的方式传递ds)
<bean class="org.apache.commons.dbutils.QueryRunner" id="queryRunner">
    <constructor-arg name="ds" ref="c3p0DataSource"></constructor-arg>
</bean>


<bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password"></property>
</bean>

* 基于注解的配置
@Configuration //作为注解文件被识别
@PropertySource("classpath:jdbcConfig.properties")//拆分引入数据库配置文件
@ComponentScan({"com.qin","Config"})    //扫描文件
public class SpringConfig {
    //配置jdbc的连接数据
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    @Bean
    public QueryRunner getQueryRunner(DataSource dataSource){
    return new QueryRunner(dataSource);
    }
    @Bean
    public DataSource getDataSource(){
    try {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(username);
        comboPooledDataSource.setPassword(password);
        return comboPooledDataSource;
    } catch (PropertyVetoException e) {
        e.printStackTrace();
        return null;
    }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值