数据库连接池和DBUtils使用

r囧r小猫 2023-06-22 06:24 20阅读 0赞

DAO模式、连接池和DBUtils应用

回顾

  1. 1、批处理
  2. Statement
  3. addBatch(Sql);
  4. executeBath();
  5. clearBath();
  6. PreparedStatement
  7. addBatch();
  8. executeBath();
  9. clearBath();
  10. 2、事务
  11. 把一组操作当成整体,不能分割,全部执行成功,都不执行。
  12. A 原子性: 不能分割
  13. C 一致性:事务执行前和执行后数据保持一致
  14. I 隔离性: 事务与事务之间的隔离
  15. D 持久性:事务提交,数据就永久保存,不能再更改。
  16. 3.事务隔离性
  17. read uncommitted 读取未提交的 (脏读)
  18. read comitted 读取提交的 (不可重复读)
  19. repeatable read 重复读 (幻读、虚读) mysql 通过并发机制解决
  20. serializable 串读 共享锁 效率低
  21. 4jdbc操作事务
  22. 0 导入驱动包
  23. 1 注册驱动
  24. 2 获取连接
  25. //开启事务 connection.setAutoCommit(false);//start transaction;
  26. 3 创建命令
  27. 4 执行命令处理结果
  28. //提交 connection.commit(); //commit;
  29. //异常 connection.rollback();//rollback;
  30. connection.commit();
  31. 5 释放资源
  32. 5 保存点 SavePoint

今日内容

  1. 1、数据库工具类封装
  2. 2DAO模式
  3. 3、使用DBCP连接池
  4. 4、使用C3P0连接池
  5. 5、使用Druid连接池
  6. 6DbUtils的使用

教学目标

  1. 1、掌握工具类的封装
  2. 2、掌握DAO设计模式
  3. 3、了解DBCP连接池
  4. 4、掌握C3P0连接池的使用
  5. 5、掌握Druid连接池的使用
  6. 6、掌握DbUtils的使用

第一节 工具类封装、DAO模式和自定义连接池

1.1 工具类封装

案例实现:实现emp表的查询、添加、删除、修改

1.1.1 封装DbUtils

由于多个地方都需要使用数据库连接和释放,所以把功能封装到工具类中DbUtils

四个功能:1注册驱动 2 获取连接 3 释放资源 4 执行命令

  1. public class DbUtils {
  2. private static String driver;
  3. private static String url;
  4. private static String user;
  5. private static String password;
  6. static{
  7. try {
  8. driver="com.mysql.jdbc.Driver";
  9. url="jdbc:mysql://localhost:3306/school";
  10. user="root";
  11. password="root";
  12. //加载驱动
  13. Class.forName(driver);
  14. } catch (Exception e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. }
  19. /**
  20. * 获取连接
  21. * @return
  22. * @throws SQLException
  23. */
  24. public static Connection getConnection() throws SQLException{
  25. return DriverManager.getConnection(url,user,password);
  26. }
  27. /**
  28. * 释放资源
  29. * @param rs
  30. * @param stat
  31. * @param conn
  32. */
  33. public static void release(ResultSet rs,Statement stat,Connection conn){
  34. if(rs!=null){
  35. try {
  36. rs.close();
  37. } catch (SQLException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. }
  41. }
  42. if(stat!=null){
  43. try {
  44. stat.close();
  45. } catch (SQLException e) {
  46. // TODO Auto-generated catch block
  47. e.printStackTrace();
  48. }
  49. }
  50. if(conn!=null){
  51. try {
  52. conn.close();
  53. } catch (SQLException e) {
  54. // TODO Auto-generated catch block
  55. e.printStackTrace();
  56. }
  57. }
  58. }
  59. /**
  60. * 根据参数执行sql语句 Insert Delete Update
  61. * @param sql
  62. * @param params
  63. * @return
  64. */
  65. public static int executeUpdate(String sql, Object...params){
  66. Connection conn=null;
  67. PreparedStatement pstat=null;
  68. try {
  69. //1创建连接
  70. conn=getConnection();
  71. //2创建命令对象
  72. pstat=conn.prepareStatement(sql);
  73. //3设置参数
  74. for (int i = 0; i < params.length; i++) {
  75. pstat.setObject(i+1, params[i]);
  76. }
  77. //4执行
  78. int result=pstat.executeUpdate();
  79. return result;
  80. } catch (Exception e) {
  81. throw new RuntimeException(e);
  82. }finally {
  83. release(null, pstat, conn);
  84. }
  85. }
  86. }

1.1.2优化DbUtils工具类:把数据库连接信息封装到Properties文件中

  1. Properties properties=new Properties();
  2. InputStream is=DbUtils.class.getClassLoader().getResourceAsStream("database.properties");
  3. properties.load(is);
  4. //初始化参数
  5. driver=properties.getProperty("driver");
  6. url=properties.getProperty("url");
  7. user=properties.getProperty("user");
  8. password=properties.getProperty("password");
1.2 DAO设计模式

DAO(Database Access Object 数据库访问对象)

为了降低耦合性,提出了DAO封装数据库操作的设计模式。

它可以实现业务逻辑与数据库访问相分离。相对来说,数据库是比较稳定的,其中DAO组件依赖于数据库系统,提供数据库访问的接口。

隔离了不同的数据库实现。

DAO模式的组成部分

1 DAO接口(主要 添加 修改 更新 删除方法)

2 DAO实现类

3 实体类 (domain、beans、entity、pojo、model)

--作用:用在数据访问代码和业务逻辑代码之间通过实体类来传输数据

--实体类特征:

◦属性一般使用private修饰

◦提供public修饰的getter/setter方法

◦实体类提供无参构造方法,根据业务提供有参构造

◦实现java.io.Serializable接口,支持序列化机制

4 数据库连接和关闭工具类

设计的包名 :

domain 存放实体类

utils 存放工具类

dao 存放接口

dao.impl 存放实现类

使用DAO设计模式实现emp表的查询、添加、删除、修改

Employee类

  1. /**
  2. * 员工类
  3. * 实体类
  4. * @author wgy
  5. *
  6. */
  7. public class Employee implements Serializable {
  8. /**
  9. *
  10. */
  11. private static final long serialVersionUID = 373910607014836778L;
  12. private int empno;
  13. private String ename;
  14. private String job;
  15. private int mgr;
  16. private Date hiredate;
  17. private double sal;
  18. private double comm;
  19. private int deptno;
  20. public Employee() {
  21. // TODO Auto-generated constructor stub
  22. }
  23. public Employee(int empno, String ename, String job, int mgr, Date hiredate, double sal, double comm, int deptno) {
  24. super();
  25. this.empno = empno;
  26. this.ename = ename;
  27. this.job = job;
  28. this.mgr = mgr;
  29. this.hiredate = hiredate;
  30. this.sal = sal;
  31. this.comm = comm;
  32. this.deptno = deptno;
  33. }
  34. public int getEmpno() {
  35. return empno;
  36. }
  37. public void setEmpno(int empno) {
  38. this.empno = empno;
  39. }
  40. public String getEname() {
  41. return ename;
  42. }
  43. public void setEname(String ename) {
  44. this.ename = ename;
  45. }
  46. public String getJob() {
  47. return job;
  48. }
  49. public void setJob(String job) {
  50. this.job = job;
  51. }
  52. public int getMgr() {
  53. return mgr;
  54. }
  55. public void setMgr(int mgr) {
  56. this.mgr = mgr;
  57. }
  58. public Date getHiredate() {
  59. return hiredate;
  60. }
  61. public void setHiredate(Date hiredate) {
  62. this.hiredate = hiredate;
  63. }
  64. public double getSal() {
  65. return sal;
  66. }
  67. public void setSal(double sal) {
  68. this.sal = sal;
  69. }
  70. public double getComm() {
  71. return comm;
  72. }
  73. public void setComm(double comm) {
  74. this.comm = comm;
  75. }
  76. public int getDeptno() {
  77. return deptno;
  78. }
  79. public void setDeptno(int deptno) {
  80. this.deptno = deptno;
  81. }
  82. @Override
  83. public String toString() {
  84. return "Employee [empno=" + empno + ", ename=" + ename + ", job=" + job + ", mgr=" + mgr + ", hiredate="
  85. + hiredate + ", sal=" + sal + ", comm=" + comm + ", deptno=" + deptno + "]";
  86. }
  87. }

接口:

  1. public interface EmployeeDao {
  2. //1查询
  3. List<Employee> findAll();
  4. //2更新
  5. void update(Employee e);
  6. //3删除
  7. void delete(int empno);
  8. //4添加
  9. void add(Employee e);
  10. }

实现类

  1. public class EmployeeDaoImpl implements EmployeeDao{
  2. @Override
  3. public List<Employee> findAll() {
  4. ArrayList<Employee> employees=new ArrayList<Employee>();
  5. //1获取连接
  6. Connection conn=null;
  7. PreparedStatement pstat=null;
  8. ResultSet rs=null;
  9. try {
  10. conn=DbUtils.getConnection();
  11. pstat=conn.prepareStatement("select * from emp;");
  12. rs=pstat.executeQuery();
  13. while(rs.next()){
  14. int empno=rs.getInt("empno");
  15. String ename=rs.getString("ename");
  16. String job=rs.getString("job");
  17. int mgr=rs.getInt("mgr");
  18. Date date=rs.getDate("hiredate");
  19. double sal=rs.getDouble("sal");
  20. double comm=rs.getDouble("comm");
  21. int deptno=rs.getInt("deptno");
  22. Employee employee=new Employee(empno, ename, job, mgr, date, sal, comm, deptno);
  23. employees.add(employee);
  24. }
  25. return employees;
  26. } catch (Exception e) {
  27. throw new RuntimeException("查询emp失败");
  28. } finally {
  29. DbUtils.closeAll(rs, pstat, conn);
  30. }
  31. }
  32. @Override
  33. public void update(Employee e) {
  34. Object[] params={
  35. e.getEname(),e.getJob(),e.getMgr(),e.getHiredate(),e.getSal(),e.getComm(),e.getDeptno(),e.getEmpno()};
  36. DbUtils.executeUpdate("update emp set ename=?,job=?,mgr=?,hiredate=?,sal=?,comm=?,deptno=? where empno=?", params);
  37. }
  38. @Override
  39. public void delete(int empno) {
  40. DbUtils.executeUpdate("delete from emp where empno=?", empno);
  41. }
  42. @Override
  43. public void add(Employee e) {
  44. Object[] params={
  45. e.getEmpno(),e.getEname(),e.getJob(),e.getMgr(),e.getHiredate(),e.getSal(),e.getComm(),e.getDeptno()};
  46. DbUtils.executeUpdate("insert into emp values(?,?,?,?,?,?,?,?)", params);
  47. }
  48. }
1.3 自定义实现连接池

为什么要使用连接池:

用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长。假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大的浪费数据库的资源,并且极易造成数据库服务器内存溢出、拓机。

Java为连接池实现提供了一个规范(接口),规范的写法,我们需要实现DataSource接口!

  1. /**
  2. * 连接池
  3. * @author wgy
  4. *
  5. */
  6. public class MyDbPool implements DataSource{
  7. //创建集合 并且线程安全
  8. public static List<Connection> connctions=Collections.synchronizedList(new LinkedList<Connection>()) ;
  9. static{
  10. try {
  11. InputStream is=MyDbPool.class.getClassLoader().getResourceAsStream("database.properties");
  12. Properties properties=new Properties();
  13. properties.load(is);
  14. String driver=properties.getProperty("driver");
  15. String url=properties.getProperty("url");
  16. String user=properties.getProperty("user");
  17. String password=properties.getProperty("password");
  18. //1加载驱动
  19. Class.forName(driver);
  20. for(int i=0;i<5;i++){
  21. Connection connection=DriverManager.getConnection(url, user, password);
  22. connctions.add(connection);
  23. System.out.println(i+"....."+connection.hashCode());
  24. }
  25. } catch (Exception e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. }
  30. @Override
  31. public Connection getConnection() throws SQLException {
  32. // TODO Auto-generated method stub
  33. Connection connection=connctions.remove(0);
  34. System.out.println("获取一个连接.."+connection.hashCode());
  35. System.out.println("池中还剩"+connctions.size());
  36. return connection;
  37. }
  38. @Override
  39. public Connection getConnection(String username, String password) throws SQLException {
  40. // TODO Auto-generated method stub
  41. return null;
  42. }
  43. /**
  44. * 把连接再放入池中
  45. * @param conn
  46. */
  47. public void release(Connection conn){
  48. connctions.add(conn);
  49. System.out.println("放入了一个连接"+conn.hashCode());
  50. System.out.println("池中还剩"+connctions.size());
  51. }
  52. @Override
  53. public PrintWriter getLogWriter() throws SQLException {
  54. // TODO Auto-generated method stub
  55. return null;
  56. }
  57. @Override
  58. public void setLogWriter(PrintWriter out) throws SQLException {
  59. // TODO Auto-generated method stub
  60. }
  61. @Override
  62. public void setLoginTimeout(int seconds) throws SQLException {
  63. // TODO Auto-generated method stub
  64. }
  65. @Override
  66. public int getLoginTimeout() throws SQLException {
  67. // TODO Auto-generated method stub
  68. return 0;
  69. }
  70. @Override
  71. public Logger getParentLogger() throws SQLFeatureNotSupportedException {
  72. // TODO Auto-generated method stub
  73. return null;
  74. }
  75. @Override
  76. public <T> T unwrap(Class<T> iface) throws SQLException {
  77. // TODO Auto-generated method stub
  78. return null;
  79. }
  80. @Override
  81. public boolean isWrapperFor(Class<?> iface) throws SQLException {
  82. // TODO Auto-generated method stub
  83. return false;
  84. }
  85. }

第二节 DBCP连接池

DBCP(DataBase connection pool),[数据库连接池]。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要2个包:commons-dbcp.jar,commons-pool.jar由于建立数据库连接是一个非常耗时的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。

#####2.1 DBCP连接池的使用

2.1.1 创建项目

创建JavaWeb项目

2.1.2 导入相应jar包

mysql驱动包

commons-dbcp.jar

commons-pool.jar

commons-logging.jar 日志支持

2.1.3 硬编码使用DBCP

所谓的硬编码方式就是在代码中添加配置

  1. @Test
  2. public void testHard() throws SQLException{
  3. //TODO 硬编码 使用DBCP连接池子
  4. BasicDataSource source = new BasicDataSource();
  5. //设置连接的信息
  6. source.setDriverClassName("com.mysql.jdbc.Driver");
  7. source.setUrl("jdbc:mysql://localhost:3306/day2");
  8. source.setUsername("root");
  9. source.setPassword("111");
  10. Connection connection = source.getConnection();
  11. String sql = "select * from student";
  12. Statement createStatement = connection.createStatement();
  13. ResultSet executeQuery = createStatement.executeQuery(sql);
  14. while (executeQuery.next()) {
  15. System.out.println(executeQuery.getString(2));
  16. }
  17. connection.close(); //回收
  18. }
2.1.4 软编码使用DBCP

所谓的软编码,就是在项目中添加配置文件,这样就不需要每次代码中添加配合!

  1. 项目中添加配置

文件名称: dbcp.properties

文件位置: src下

  1. #连接设置
  2. driverClassName=com.mysql.jdbc.Driver
  3. url=jdbc:mysql://localhost:3306/school
  4. username=root
  5. password=root
  6. #<!-- 初始化连接 -->
  7. initialSize=10
  8. #最大连接数量
  9. maxTotal=50
  10. #<!-- 最大空闲连接 -->
  11. maxIdle=20
  12. #<!-- 最小空闲连接 -->
  13. minIdle=5
  14. #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
  15. maxWaitMillis=5000
  1. 代码实现

    @Test

    1. public void testSoft() throws Exception{
    2. Properties properties = new Properties();
    3. //配置文件添加到properties对象中 javase
    4. properties.load(new FileInputStream("src/info.properties"));
    5. //生成连接池子 需要配置文件
    6. DataSource source = BasicDataSourceFactory.createDataSource(properties);
    7. Connection connection = source.getConnection();
    8. String sql = "select * from student";
    9. Statement createStatement = connection.createStatement();
    10. ResultSet executeQuery = createStatement.executeQuery(sql);
    11. while (executeQuery.next()) {
    12. System.out.println(executeQuery.getString(2));
    13. }
    14. connection.close(); //回收
    15. }

第三节 C3P0连接池

C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等。

  1. c3p0dbcp区别
  2. 1.
  3. dbcp没有自动回收空闲连接的功能
  4. c3p0有自动回收空闲连接功能
  5. 2.
  6. dbcp需要手动加载配置文件
  7. c3p0自动加载
3.1 使用步骤
3.1.1 创建项目
3.1.2 导入jar包

c3p0-0.9.1.2.jar

mchange-commons-java-0.2.11.jar

mysql驱动包

3.1.3.添加配置文件

c3p0是在外部添加配置文件,工具直接进行应用,因为直接引用,所以要求固定的命名和文件位置

文件位置: src

文件命名:c3p0-config.xml/c3p0.properties

  1. <c3p0-config>
  2. <!-- 默认配置,如果没有指定则使用这个配置 -->
  3. <default-config>
  4. <!-- 基本配置 -->
  5. <property name="driverClass">com.mysql.jdbc.Driver</property>
  6. <property name="jdbcUrl">jdbc:mysql://localhost:3306/school</property>
  7. <property name="user">root</property>
  8. <property name="password">root</property>
  9. <!--扩展配置-->
  10. <!-- 连接超过10秒报错-->
  11. <property name="checkoutTimeout">10000</property>
  12. <!--30秒检查空闲连接 -->
  13. <property name="idleConnectionTestPeriod">30</property>
  14. <!-- 初始大小 -->
  15. <property name="initialPoolSize">10</property>
  16. <!-- 每次增长的个数 -->
  17. <property name="acquireIncrement">5</property>
  18. <!-- 30秒不适用丢弃-->
  19. <property name="maxIdleTime">20</property>
  20. <property name="maxPoolSize">50</property>
  21. <property name="minPoolSize">5</property>
  22. </default-config>
  23. <!-- 命名的配置 -->
  24. <named-config name="bj1805">
  25. <property name="driverClass">com.mysql.jdbc.Driver</property>
  26. <property name="jdbcUrl">jdbc:mysql://localhost:3306/day2</property>
  27. <property name="user">root</property>
  28. <property name="password">111</property>
  29. <!-- 如果池中数据连接不够时一次增长多少个 -->
  30. <property name="acquireIncrement">5</property>
  31. <property name="initialPoolSize">20</property>
  32. <property name="minPoolSize">10</property>
  33. <property name="maxPoolSize">40</property>
  34. </named-config>
  35. </c3p0-config>

c3p0.properties

  1. c3p0.driverClass=com.mysql.jdbc.Driver
  2. c3p0.jdbcUrl=jdbc:mysql://localhost:3306/school
  3. c3p0.user=root
  4. c3p0.password=root
  5. c3p0.acquireIncrement=5
  6. c3p0.initialPoolSize=20
  7. c3p0.minPoolSize=10
  8. c3p0.maxPoolSize=40

注意:

1: c3p0的配置文件内部可以包含命名配置文件和默认配置文件!默认是选择默认配置!如果需要切换命名配置可以在创建c3p0连接池的时候填入命名即可!

2:如果xml配置文件和属性文件都存在时,xml优先级高于属性文件

3.1.4 c3p0进行数据库操作
  1. public class TestC3p0 {
  2. public static void main(String[] args) throws Exception {
  3. //创建ComboPooledDataSource对象使用默认配置
  4. ComboPooledDataSource dataSource = new ComboPooledDataSource();
  5. //1.创建C3P0连接池子
  6. Connection connection = dataSource.getConnection();
  7. Statement createStatement = connection.createStatement();
  8. String sql = "select * from student;";
  9. ResultSet resultSet = createStatement.executeQuery(sql);
  10. while (resultSet.next()) {
  11. System.out.println(resultSet.getString(1));
  12. }
  13. resultSet.close();
  14. createStatement.close();
  15. connection.close();
  16. }
  17. }

第四节 Druid连接池

  1. Druid 是目前比较流行的高性能的,分布式列存储的OLAP框架(具体来说是MOLAP)。它有如下几个特点:
  2. 一. 亚秒级查询
  3. druid提供了快速的聚合能力以及亚秒级的OLAP查询能力,多租户的设计,是面向用户分析应用的理想方式。
  4. 二.实时数据注入
  5. druid支持流数据的注入,并提供了数据的事件驱动,保证在实时和离线环境下事件的实效性和统一性
  6. 三.可扩展的PB级存储
  7. druid集群可以很方便的扩容到PB的数据量,每秒百万级别的数据注入。即便在加大数据规模的情况下,也能保证时其效性
  8. 四.多环境部署
  9. druid既可以运行在商业的硬件上,也可以运行在云上。它可以从多种数据系统中注入数据,包括hadoopsparkkafkastormsamza
  10. 五.丰富的社区
  11. druid拥有丰富的社区,供大家学习
4.1 使用步骤

配置文件 database.properties:

  1. #连接设置
  2. driverClassName=com.mysql.jdbc.Driver
  3. url=jdbc:mysql://localhost:3306/school
  4. username=root
  5. password=root
  6. #<!-- 初始化连接 -->
  7. initialSize=10
  8. #最大连接数量
  9. maxActive=50
  10. #<!-- 最小空闲连接 -->
  11. minIdle=5
  12. #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
  13. maxWait=5000
4.1.1 导入jar包

druid-1.1.5.jar

4.1.2 编写工具类
  1. /**
  2. * 阿里的数据库连接池
  3. * 性能最好的
  4. * Druid
  5. * */
  6. public class DbUtils {
  7. //声明连接池对象
  8. private static DruidDataSource ds;
  9. static{
  10. //实例化配置对象
  11. Properties properties=new Properties();
  12. try {
  13. //加载配置文件内容
  14. properties.load(DbUtils.class.getResourceAsStream("database.properties"));
  15. ds = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
  16. } catch (IOException e) {
  17. // TODO Auto-generated catch block
  18. e.printStackTrace();
  19. }
  20. }
  21. //获取连接对象
  22. public static Connection getConnection() {
  23. try {
  24. return ds.getConnection();
  25. } catch (SQLException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. return null;
  30. }
  31. }
4.1.3 测试
  1. package com.qf.utils;
  2. import java.sql.Connection;
  3. public class Test {
  4. public static void main(String[] args) throws Exception {
  5. for(int i=0;i<100;i++) {
  6. Connection connection=DbUtils.getConnection();
  7. if(connection!=null) {
  8. System.out.println("连接成功"+i+"..."+connection.hashCode()+connection.toString());
  9. }
  10. connection.close();
  11. }
  12. }
  13. }

第五节 DBUtils使用

Commons DbUtils是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能够简化JDBC应用程序的开发,同时也不会影响程序的性能。

5.1 DBUtils简介

DBUtils是java编程中的数据库操作实用工具,小巧简单实用,

1.对于数据表的读操作,可以把结果转换成List,Array,Set等java集合,便于程序员操作。

2.对于数据表的写操作,也变得很简单(只需写sql语句)。

DBUtils包括主要类

DbUtils类:启动类

ResultSetHandler接口:转换类型接口

--ArrayHandler类:实现类,把记录转化成数组

--ArrayListHandler类:把记录转化成数组,并放入集合中

--ColumnListHandler类:取某一列的数据。封装到List中。

--ScalarHandler类:适合获取一行一列数据。

--BeanHandler类:实现类,把记录转成对象。

--BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象

QueryRunner类:执行SQL语句的类

5.2 DBUtils工具类封装
5.2.1 项目准备
  • 创建项目
  • 导入jar包 工具类 配置文件
    commons-dbutils-1.6.jar
    druid-1.1.5.jar
    DruidUtils.java工具类
    database.properties配置文件
5.2.2 实现代码
  1. public class ResultHanlder {
  2. @Test
  3. public void testArrayHander() throws SQLException {
  4. // ArrayHandler:适合取1条记录。把该条记录的每列值封装到一个数组中Object[]
  5. QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
  6. Object[] query = runner.query("select * from school where empno = ?", new ArrayHandler(), 1234);
  7. for (Object object : query) {
  8. System.out.println(object);
  9. }
  10. }
  11. @Test
  12. public void testArrayListHander() throws SQLException {
  13. // ArrayHandler:适合取1条记录。把该条记录的每列值封装到一个数组中Object[]
  14. QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
  15. List<Object[]> query = runner.query("select * from emp ", new ArrayListHandler());
  16. for (Object[] objects : query) {
  17. for (Object object : objects) {
  18. System.out.println(object);
  19. }
  20. }
  21. }
  22. @Test
  23. public void testColumnListHander() throws SQLException {
  24. // ColumnListHandler:取某一列的数据。封装到List中。
  25. QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
  26. List<Object> query = runner.query("select * from emp ", new ColumnListHandler<Object>(2));
  27. for (Object objects : query) {
  28. System.out.println(objects);
  29. }
  30. }
  31. @Test
  32. public void testScalarHandler() throws SQLException {
  33. // ScalarHandler:适合取单行单列数据
  34. QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
  35. Object query = runner.query("select count(*) from emp ", new ScalarHandler());
  36. System.out.println(query);
  37. }
  38. @Test
  39. public void testBeanHandler() throws SQLException {
  40. // BeanHandler:适合取单行单列数据
  41. QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
  42. Employee query = runner.query("select * from emp where empno=1234 ", new BeanHandler<Employee>(Employee.class));
  43. System.out.println(query.toString());
  44. }
  45. @Test
  46. public void testBeanListHandler() throws SQLException {
  47. // BeanHandler:适合取多行多列数据
  48. QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
  49. List<Employee> query2 = runner.query("select * from emp", new BeanListHandler<Employee>(Employee.class));
  50. for (Employee employee : query2) {
  51. System.out.println(employee);
  52. }
  53. }
  54. }

总结

1 封装工具类

2 Dao设计模式: 把数据访问代码抽离出来。降低代码的耦合性和提高扩展性。

dao接口

dao实现

实体类

数据库工具类

3 连接池

dbcp

c3p0

druid重点

4 Dbutils工具

作业题

  1. 1、使用数据库连接池和DbUtils改造之前的案例

面试题

  1. 1、描述数据库连接池的优缺点

发表评论

表情:
评论列表 (有 0 条评论,20人围观)

还没有评论,来说两句吧...

相关阅读