[八]数据库连接池与JDBC。纳尼?连接池关JDBC神马事?
起源
为何放弃DriverManager
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//数据库连接所需参数
String user = "root";
String password = "123456";
String url = "jdbc:mysql://localhost:3306/sampledb?useUnicode=true&characterEncoding=utf-8";
//2、获取连接对象
Connection conn = DriverManager.getConnection(url, user, password);
连接池
数据源
实现
核心架构
DataSource
基本实现 - 生成标准的 Connection 对象
连接池实现 - 生成自动参与连接池的 Connection 对象。此实现与中间层连接池管理器一起使用。
分布式事务实现 - 生成一个 Connection 对象,该对象可用于分布式事务,大多数情况下总是参与连接池。此实现与中间层事务管理器一起使用,大多数情况下总是与连接池管理器一起使用。
API
Connection getConnection()
Connection getConnection(String username, String password)
小结
应用
数据库连接池示例
package jdbc;
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.dbcp2.BasicDataSource;
public class MyDataSource {
public static void main(String[] args) throws Exception {
String user = "root";
String password = "123456";
String url = "jdbc:mysql://localhost:3306/sampledb?useUnicode=true&characterEncoding=utf-8";
//1.获取连接
// Connection conn = getDHCPConnection(user,password,url);
//Connection conn = getC3P0Connection(user,password,url);
Connection conn = getDruidConnection(user, password, url);
String sql = "select * from student limit 0,10";
//2、获得sql语句执行对象
Statement stmt = conn.createStatement();
//3、执行并保存结果集
ResultSet rs = stmt.executeQuery(sql);
//4、处理结果集
while (rs.next()) {
System.out.print("id:" + rs.getInt(1));
System.out.print(",姓名:" + rs.getString(2));
System.out.print(",年龄:" + rs.getInt(3));
System.out.println(",性别:" + rs.getString(4));
}
conn.close();
stmt.close();
rs.close();
}
public static Connection getDruidConnection(String user, String password, String url)
throws Exception {
DruidDataSource ds = new DruidDataSource();
ds.setUsername(user);
ds.setPassword(password);
ds.setUrl(url);
ds.setDriverClassName("com.mysql.jdbc.Driver");
return ds.getConnection();
}
public static Connection getC3P0Connection(String user, String password, String url)
throws Exception {
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setUser(user);
cpds.setPassword(password);
cpds.setJdbcUrl(url);
cpds.setDriverClass("com.mysql.jdbc.Driver");
return cpds.getConnection();
}
public static Connection getDHCPConnection(String user, String password, String url)
throws Exception {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
Connection connection = dataSource.getConnection();
return connection;
}
}
总结
··················END··················
注:非技术讲解配图均来源于网络
期待分享
如果对你有用
你「在看」吗? ↓↓