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;
}
}
}