Java使用C3P0数据源链接数据库
人气:01、相关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内容如下
<?xml version="1.0" encoding="utf-8" ?> <c3p0-config> <default-config> <property name="user">root</property> <property name="password">1234</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> jdbc:mysql://localhost:3306/chapter02 </property> <property name="checkoutTimeout">30000</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <named-config name="dongyao"> <property name="initialPoolSize">5</property> <property name="maxPoolSize">15</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> jdbc:mysql://localhost:3306/chapter02 </property> <property name="user">root</property> <property name="password">1234</property> </named-config> </c3p0-config>
其中<default-config>是默认配置,<named-config name=””>是自定义配置,一个配置文件中可以有一个或者多个自定义配置,调用ComboPoolDataSource(String configName)方法传入<named-config>节点中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、控制台显示
您可能感兴趣的文章:
加载全部内容