当用户多的时候,每次打开关闭连接 会很耗资源和时间,所以连接池的作用就有了;
以C3P0连接池 为例:
C3P0连接池
C3P0简介
C3P0也是开源免费的连接池,现在做的大部分项目都是使用C3P0连接池。
C3P0的使用
C3P0中池类是:ComboPooledDataSource。
简单的操作:
//导入C3P0jar包,新建一个DBUtils类,如下
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBUtils {
public static Connection initConnection() {
try {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
String url = "jdbc:mysql://localhost:3306/test";
dataSource.setJdbcUrl(url);
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
Connection connection = dataSource.getConnection();
return connection;
} catch (PropertyVetoException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
//然后 新建一个Main类
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws SQLException {
String ClassName = "com.mysql.jdbc.Driver";//固定格式
String url = "jdbc:mysql://localhost:3306/test";//test是在mysql下自定义建立的数据库
String userName = "root";//mysql的user,就是你在安装mysql时设定的用户名,和下面的用户密码 同理
String password = "root";
Connection connect = null;
PreparedStatement statement1 = null;
try {
Class.forName(ClassName);
//connect = DriverManager.getConnection(url, userName, password);
//改成从连接池中取返回的connection
connect = DBUtils.initConnection();
System.out.println("Success connent the Mysql server");
String sql = "select * from user";
statement1 = connect.prepareStatement(sql);
ResultSet rSet = statement1.executeQuery();
while ( rSet.next() ) {
System.out.print(rSet.getString("name"));
System.out.print(" ");
System.out.println(rSet.getString("password"));
}
} catch (ClassNotFoundException e) {
System.out.println("Error loading Mysql Driver");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//关闭流
statement1.close();
//关闭连接
connect.close();
}
}
}
实现了如下结果: