我们都知道通过jdbc 的链接 会消耗大量的连接,每一次连接都会消耗资源,关闭》打开都是要消耗资源的,频繁的建立、关闭连接,会极大的减低系统的性能,因为对于连接的使用成了系统性能的瓶颈。
数据库连接池技术带来的优势:
1. 资源重用
2. 更快的系统响应速度
3. 新的资源分配手段
4. 统一的连接管理,避免数据库连接泄漏
原理图解
使用过程:
jdbc.properties
DriverClass = com.mysql.jdbc.Driver
JdbcUrl = jdbc\:mysql\://ID\:3306/htmldata?useUnicode\=true&characterEncoding\=UTF-8
User = root
Password = 123
MaxPoolSize = 20
MinPoolSize = 2
InitialPoolSize = 5
MaxStatements = 30
MaxIdleTime =100
C3P0Mysql.java
package class_name;
import java.sql.Connection;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Mysql {
private ComboPooledDataSource cpds;
private static C3P0Mysql c3P0Properties;
static{
c3P0Properties = new C3P0Mysql();
}
public C3P0Mysql() {
try {
cpds = new ComboPooledDataSource();
//加载配置文件
Properties props = new Properties();
props.load(C3P0Mysql.class.getClassLoader().getResourceAsStream("jdbc.properties"));
cpds.setDriverClass(props.getProperty("DriverClass"));
cpds.setJdbcUrl(props.getProperty("JdbcUrl"));
cpds.setUser(props.getProperty("User"));
cpds.setPassword(props.getProperty("Password"));
cpds.setMaxPoolSize(Integer.parseInt(props.getProperty("MaxPoolSize")));
cpds.setMinPoolSize(Integer.parseInt(props.getProperty("MinPoolSize")));
cpds.setInitialPoolSize(Integer.parseInt(props.getProperty("InitialPoolSize")));
cpds.setMaxStatements(Integer.parseInt(props.getProperty("MaxStatements")));
cpds.setMaxIdleTime(Integer.parseInt(props.getProperty("MaxIdleTime")));
} catch (Exception e) {
e.printStackTrace();
}
}
public static C3P0Mysql getInstance(){
return c3P0Properties;
}
public Connection getConnection(){
Connection conn = null;
try {
conn = cpds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection connection = C3P0Mysql.c3P0Properties.getConnection();
System.out.println("已经连接成功");
}
}