在src文件下建立c3p0.properties文件,内容如下图
然后导入c3p0 jar包
连接代码如下:
package c3p0;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Test {
@Test
public void fun1() throws Exception {
// 获取ComboPooledDataSource对象
// 它会自动根据默认的配置文件的名字去找对应的配置文件
ComboPooledDataSource cpds = new ComboPooledDataSource();
// 获取数据库连接
Connection conn = cpds.getConnection();
// 准备sql语句
String sql = "select *from student";
// 创建执行者对象(预编译)
PreparedStatement ptmt = conn.prepareStatement(sql);
// 执行sql语句
ResultSet rs = ptmt.executeQuery();
// 处理数据
while (rs.next()) {
System.out.println(rs.getString("Sno") + "\t" + rs.getString("Sname") + "\t" + rs.getString("Ssex") + "\t"
+ rs.getInt("Sage") + "\t" + rs.getString("Sdept") + "\t" + rs.getString("S_entrance"));
}
// 释放资源(rs - stmt - conn)
rs.close();
ptmt.close();
conn.close();
}
}