C3P0
1、添加jar包
c3p0-0.9.1.2.jar
mysql-connector-java-5.0.8-bin.jar
2、在src下创建C3P0的配置文件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/db1</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">15</property>
<property name="maxIdleTime">40</property>
<property name="maxPoolSize">150</property>
<property name="minPoolSize">20</property>
</default-config>
</c3p0-config>
3、编写操作C3P0的工具类C3P0Util
package com.etime;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Util {
//创建数据库连接池
private static DataSource dataSource = new ComboPooledDataSource();
//创建连接
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
System.out.println("获取数据库连接失败:" + e.toString());
}
return null;
}
//释放连接
public static void release(Connection connection,Statement statement,ResultSet resultSet) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (statement != null) {
try {
statement .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4、使用C3P0
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = C3P0Util.getConnection();
String sql = "select * from student";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
int studentId = resultSet.getInt("studentid");
String studentName = resultSet.getString("studentname");
Student student = new Student(studentId,studentName);
System.out.println(student);
}
} catch (Exception e) {
System.out.println(e.toString());
}finally {
C3P0Util.release(connection, preparedStatement, resultSet);
}
}