本文实例为大家分享了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
其中
在项目的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、控制台显示
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



