怎么在Java中利用C3P0数据源连接数据库

怎么在Java中利用C3P0数据源连接数据库?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

黄龙网站建设公司创新互联公司,黄龙网站设计制作,有大型网站制作公司丰富经验。已为黄龙上1000+提供企业网站建设服务。企业网站搭建\成都外贸网站制作要多少钱,请找那个售后服务好的黄龙做网站的公司定做!

1、相关jar包,这里需要3个jar包

怎么在Java中利用C3P0数据源连接数据库

2、具体链接数据库代码

ComboPooledDataSource类继承自AbstractComboPooledDataSource类,且AbstractComboPooledDataSource类实现了PooledDataSource接口

ComboPooledDataSource常用方法

怎么在Java中利用C3P0数据源连接数据库

(1)、通过ComboPooledDataSource类直接创建数据源对象

Example4.java

import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.SQLException;
public class Example4{
  public static DataSource dataSource = null;
  //初始化C3P0数据源
  static {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    try{
      comboPooledDataSource.setDriverClass("com.MySQL.jdbc.Driver");
      comboPooledDataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/chapter02");
      comboPooledDataSource.setUser("root");
      comboPooledDataSource.setPassword("1234");
      //初始化
      comboPooledDataSource.setInitialPoolSize(5);
      //设置最大的链接数
      comboPooledDataSource.setMaxPoolSize(15);
      dataSource = comboPooledDataSource;
    }catch (Exception e){
    }
  }
  public static void main(String[] args)throws SQLException {
    System.out.println(dataSource.getConnection());
  }
}

(2)、通过配置文件创建数据源对象

在项目的src目录下创建一个出c3p0-donfig.xml文件

c3p0-donfig.xml内容如下



  
    root
    1234
    com.mysql.jdbc.Driver
    
      jdbc:mysql://localhost:3306/chapter02
    
    30000
    10
    30
    100
    10
    200
  
  
    5
    15
    com.mysql.jdbc.Driver
    
      jdbc:mysql://localhost:3306/chapter02
    
    root
    1234
  

其中是默认配置,是自定义配置,一个配置文件中可以有一个或者多个自定义配置,调用ComboPoolDataSource(String configName)方法传入节点中name属性的值即可创建C3P0数据源对象。

在项目的src目录下创建一个Example5的类

Example5.java

import com.mchange.v2.c3p0.ComboPooledDataSource;
 
import javax.sql.DataSource;
import java.sql.SQLException;
 
public class Example5 {
  public static DataSource dataSource = null;
  static {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("dongyao");
    dataSource = comboPooledDataSource;
  }
  public static void main(String[] args) throws SQLException {
    System.out.println(dataSource.getConnection());
  }
}

3、控制台显示

怎么在Java中利用C3P0数据源连接数据库

关于怎么在Java中利用C3P0数据源连接数据库问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


当前题目:怎么在Java中利用C3P0数据源连接数据库
当前网址:http://myzitong.com/article/gopjii.html