本节将演示使用DbUtils中的QueryRunner完成数据库的操作。
1、前提步骤
- 已经安装好mysql数据库,其他数据库也可以,笔者这边是mysql数据库,且账号密码为root/zhangli,请读者按照自己的实际情况完成适配
- 在数据库中执行以下语句,完成表数据的初始化
create table t_student(id int,name varchar(20));
insert into t_student(id,name) values(1,'ali');
insert into t_student(id,name) values(2,'xiaoli');
insert into t_student(id,name) values(3,'zhangli');
2、操作步骤
- 创建maven项目,加入以下依赖:
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
- 在项目的src/main/java文件夹下创建TestQueryrunner.java
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
public class TestQueryrunner {
public static void main(String[] args) throws Exception{
//获取c3p0数据源
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setUser("root");
dataSource.setPassword("zhangli");
//获取QueryRunner对象
QueryRunner queryRunner = new QueryRunner(dataSource);
//查询出所有用户
List<Student> list = queryRunner.query("select * from t_student", new BeanListHandler<Student>(Student.class));
//更新某一个用户
queryRunner.update("update t_student set name=? where id=?",new Object[]{"jiangsuwanhe",1});
//查询某一个用户
Student student = queryRunner.query("select * from t_student where id=?",new BeanHandler<Student>(Student.class),new Object[]{1});
}
}
以上就是使用QueryRunner完成数据库操作的过程。
网友评论