java 数据源连接池C3P0
1.jar包
c3p0
https://mvnrepository.com/artifact/com.mchange/c3p0/0.9.5.5
依赖
com.mchange » mchange-commons-java
2.配置文件
xml
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:8889/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=true</property>
<property name="user">root</property>
<property name="password">root</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>
<!-- This app is massive! -->
<named-config name="myConfig">
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">200</property>
</named-config>
</c3p0-config>
3.工具类
package com.myweb.lesson02.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//c3p0工具类
public class C3p0Utils {
private static DataSource dataSource = null;
static {
try {
//创建c3p0数据源
dataSource = new ComboPooledDataSource("myConfig");
} catch (Exception e) {
e.printStackTrace();
}
}
//2.获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();//从数据源中获取连接
}
//3.释放连接资源
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs != null)
{
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null)
{
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
4.测试类
package com.myweb.lesson05;
import com.myweb.lesson02.utils.C3p0Utils;
import com.myweb.lesson02.utils.DbcpUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Testc3p0 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet =null;
try {
connection = C3p0Utils.getConnection();
String sql = "select * from users";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getInt("id"));
System.out.println(resultSet.getString("NAME"));
System.out.println(resultSet.getString("PASSWORD"));
System.out.println(resultSet.getString("birthday"));
System.out.println("==华丽的分割线==");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
C3p0.release(connection,statement,resultSet);
}
}
}