在classpath下(classes)建一个名为 c3p0-config.xml 的配置文件,当使用方法
ComboPooledDataSource cpds = new ComboPooledDataSource();
初始化对象是会自动读取配置文件中的配置信息,自动连接数据库
连接数据库的代码如下
package c3p0;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class c3p0 {
public static void main(String [] args) throws PropertyVetoException, SQLException{
ComboPooledDataSource cpds = new ComboPooledDataSource();
Connection con = cpds.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select sname from student;");
System.out.println(rs.getMetaData().getColumnName(1));
while (rs.next()){
System.out.println(rs.getString(1));
}
if(con != null)con.close();
}
}
配置文件 c3p0-config.xml 内容如下
<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/stu?serverTimezone=GMT%2B8</property>
<property name="user">root</property>
<property name="password">password</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
<property name="checkoutTimeout">3000</property>
</default-config>
</c3p0-config>