Java使用C3P0数据源链接数据库

网友投稿 246 2022-12-30


Java使用C3P0数据源链接数据库

本文实例为大家分享了java使用C3P0数据源链接数据库的具体代码,供大家参考,具体内容如下

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

2、具体链接数据库代码

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

ComboPooledDataSource常用方法

(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、控制台显示


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:golang 实现接口(golang 接口类型)
下一篇:物业管理系统接口设计(物业管理系统接口设计图)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~