32 使用QueryRunner完成数据库操作

2020-08-22  本文已影响0人  张力的程序园

本节将演示使用DbUtils中的QueryRunner完成数据库的操作。

1、前提步骤

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、操作步骤

    <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>
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完成数据库操作的过程。

上一篇下一篇

猜你喜欢

热点阅读