JdbcUtils工具类(c3p0+DbUtils优化)

来源:互联网 发布:数据口径 编辑:程序博客网 时间:2024/05/19 23:53

JdbcUtils工具类

      1.初始化c3p0连接池
       2.创建DbUtils核心工具类

涉及到的包:

   c3p0包点击打开链接
   DbUtils包点击打开链接
   MySQL驱动包点击打开链接

优化代码

JdbcUtils工具
  1. package com.cn.util;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import javax.sql.DataSource;
  5. import org.apache.commons.dbutils.QueryRunner;
  6. import com.mchange.v2.c3p0.ComboPooledDataSource;
  7. /**
  8. * 工具类
  9. * 1.初始化c3p0连接池
  10. * 2.创建DbUtils核心工具类
  11. * @author liuzhiyong
  12. *
  13. */
  14. public class JdbcUtils {
  15. private static DataSource dataSource;
  16. /**
  17. * 加载一次c3p0配置文件
  18. */
  19. static{
  20. dataSource = new ComboPooledDataSource();//无参数时,默认加载src下名为c3p0-config.xml的配置文件
  21. }
  22. /**
  23. * 创建DbUtils核心工具类对象
  24. */
  25. public static QueryRunner getQueryRunner(){
  26. /*
  27. * 创建QueryRunner对象,传入连接池对象。在创建QueryRunner对象的时候,
  28. * 如果传入了数据源对象,那么在使用QueryRunner对象方法的时候,就不需要传入连接对象,会自动从数据源中获取连接(不用关闭连接)
  29. */
  30. return new QueryRunner(dataSource);
  31. }
  32. }
c3p0配置文件
  1. <c3p0-config>
  2. <!-- 默认配置 -->
  3. <default-config>
  4. <property name="jdbcUrl">jdbc:mysql:///infosystem</property>
  5. <property name="driverClass">com.mysql.jdbc.Driver</property>
  6. <property name="user">root</property>
  7. <property name="password">root</property>
  8. <property name="initialPoolSize">3</property>
  9. <property name="maxPoolSize">10</property>
  10. <property name="maxIdleTime">1</property>
  11. </default-config>
  12. </c3p0-config>
0 0