1. 创建c3p0配置文件
c3p0-config.xml (文件名必须为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"> <![CDATA[jdbc:mysql://127.0.0.1:3306/cake?useUnicode=true&characterEncoding=UTF-8&useSSL=true]]> </property> <property name="user">root</property> <property name="password">root</property> </default-config> </c3p0-config>
2. 连接数据库
import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class Test { public static void main(String[] args) throws Exception{ DataSource ds = new ComboPooledDataSource(); // 使用c3p0的数据源 Connection con = ds.getConnection(); PreparedStatement ps = con.prepareStatement("select * from goods"); ResultSet rs = ps.executeQuery(); while(rs.next()) { System.out.println(rs.getString("name")); } rs.close(); ps.close(); con.close(); } }
效果: