ApacheDbUtilsTest

点点圈 提交于 2019-12-03 08:18:29
ApacheDbUtilsTest 
package p1;

import com.DataSourceUtil;
import entity.Student;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

public class ApacheDbUtilsTest {
    public static void main(String[] args) throws Exception {
        // ArrayHandler();
        // ArrayListHandler();
        // ArrayListHandlerStudent();
        // ArrayListHandlerStudentList();
        ArrayListHandlerStudentMap();
    }

    public static void ArrayListHandlerStudentMap() throws Exception {
        DataSource dataSource = DataSourceUtil.getDataSourceC3p0();
        QueryRunner runner = new QueryRunner(dataSource);
        String sql = "select * from student where id>?";
        //此处坑 oracle默认数值类型为BigDecimal Integer更换为BigDecimal students.get(new BigDecimal(2))
        Map<Integer, Student> students = runner.query(sql, new BeanMapHandler<Integer, Student>(Student.class, "id"), 1);
        Student student = students.get(2);
        System.out.println(student.getId() + " " + student.getName());
    }

    public static void ArrayListHandlerStudentList() throws Exception {
        DataSource dataSource = DataSourceUtil.getDataSourceC3p0();
        QueryRunner runner = new QueryRunner(dataSource);
        String sql = "select * from student where id>?";
        List<Student> students = runner.query(sql, new BeanListHandler<>(Student.class), 1);
        for (Student student : students) {
            System.out.println(student.getId() + " " + student.getName());
        }
    }

    public static void ArrayListHandlerStudent() throws Exception {
        DataSource dataSource = DataSourceUtil.getDataSourceC3p0();
        QueryRunner runner = new QueryRunner(dataSource);
        String sql = "select * from student where id>?";
        Student student = runner.query(sql, new BeanHandler<>(Student.class), 1);
        System.out.println(student.getId() + " " + student.getName());
    }

    public static void ArrayListHandler() throws Exception {
        DataSource dataSource = DataSourceUtil.getDataSourceC3p0();
        QueryRunner runner = new QueryRunner(dataSource);
        String sql = "select * from student where id>?";
        List<Object[]> objects = runner.query(sql, new ArrayListHandler(), 1);
        for (Object[] objs : objects) {
            System.out.println(objs[0] + " " + objs[1]);
        }
    }

    public static void ArrayHandler() throws Exception {
        DataSource dataSource = DataSourceUtil.getDataSourceC3p0();
        QueryRunner runner = new QueryRunner(dataSource);
        String sql = "select * from student where id>?";
        Object[] objs = runner.query(sql, new ArrayHandler(), 1);
        System.out.println(objs[0]);
        System.out.println(objs[1]);
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!