您的位置:首页 > 数据库

JDBC连接数据库的四种方式:DriverManager,DataSource,DBCP,C3P0

2016-09-05 09:47 531 查看

方法1:使用java.sql.DriverManager类

驱动管理器类,用于管理所有注册的驱动程序。

(注:DataSource 接口是 JDBC 2.0 API 中的新增内容,它提供了连接到数据源的另一种方法。使用 DataSource 对象是连接到数据源的首选方法。)

常用的两个API

registerDriver(driver)  : 注册驱动类对象

ConnectiongetConnection(url,user,password);  获取连接对象

@Test
public void test1(){
Statement stmt = null;
Connection conn = null;
try {
//1.驱动注册程序  --内部执行了RegisterDriver
Class.forName("com.mysql.jdbc.Driver");

//2.获取连接对象
conn = DriverManager.getConnection(url, user, password);

//3.创建Statement
stmt = conn.createStatement();

//4.准备sql
String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))";

//5.发送sql语句,执行sql语句,得到返回结果
int count = stmt.executeUpdate(sql);

//6.输出
System.out.println("影响了"+count+"行!");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally{
//7.关闭连接(顺序:后打开的先关闭)
if(stmt!=null)
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}


方法2:使用实现了javax.sql.DataSource接口的子类

javax.sql.DataSource接口

包名:javax.sql

接口名: DataSource

作为 DriverManager 工具的替代项,DataSource 对象是获取连接的首选方法。DataSource接口由驱动程序供应商实现。共有三种类型的实现:

1. 基本实现 - 生成标准的 Connection 对象

2. 连接池实现 - 生成自动参与连接池的 Connection 对象。此实现与中间层连接池管理器一起使用。

3. 分布式事务实现 - 生成一个 Connection 对象,该对象可用于分布式事务,大多数情况下总是参与连接池。此实现与中间层事务管理器一起使用,大多数情况下总是与连接池管理器一起使用。

 

自己实现DataSource子类这种方法不常用,常用的方法可以参考方法3和方法4

 

插入一句:Sun公司约定:如果是连接池技术,都需要实现javax.sql.DataSource接口

方法3:DBCP连接池

DBCP 是 Apache 软件基金组织下的开源连接池实现,使用DBCP数据源,应用程序应在系统中增加如下两个 jar 文件:

Commons-dbcp.jar:连接池的实现

Commons-pool.jar:连接池实现的依赖库

Tomcat 的连接池正是采用该连接池来实现的。该数据库连接池既可以与应用服务器整合使用,也可由应用程序独立使用。

 

核心类:BasicDataSource

包名:org.apache.commons.dbcp

类名:ClassBasicDataSource extends Object implements DataSource

Basicimplementation of javax.sql.DataSource that is configured via JavaBeansproperties. This is not the only way to combine the commons-dbcp andcommons-pool packages, but provides a "one stop shopping" solutionfor basic requirements.

2. 两种方式实现连接池

1)硬编码方式

2)配置方式

public class App_DBCP {

// 1. 硬编码方式实现连接池
@Test
public void testDbcp() throws Exception {
// DBCP连接池核心类
BasicDataSource dataSouce = new BasicDataSource();
// 连接池参数配置:初始化连接数、最大连接数 / 连接字符串、驱动、用户、密码
dataSouce.setUrl("jdbc:mysql:///jdbc_demo");		//数据库连接字符串
dataSouce.setDriverClassName("com.mysql.jdbc.Driver");  //数据库驱动
dataSouce.setUsername("root");							//数据库连接用户
dataSouce.setPassword("root"); 							//数据库连接密码
dataSouce.setInitialSize(3);  // 初始化连接
dataSouce.setMaxActive(6);	  // 最大连接
// 获取连接
Connection con = dataSouce.getConnection();
con.prepareStatement("delete from admin where id=3").executeUpdate();
// 关闭
con.close();
}

@Test
// 2. 【推荐】配置方式实现连接池,  便于维护
public void testProp() throws Exception {
// 加载prop配置文件
Properties prop = new Properties();
// 获取文件流
InputStream inStream = App_DBCP.class.getResourceAsStream("db.properties");
// 加载属性配置文件
prop.load(inStream);
// 根据prop配置,直接创建数据源对象
DataSource dataSouce = BasicDataSourceFactory.createDataSource(prop);

// 获取连接
Connection con = dataSouce.getConnection();
con.prepareStatement("delete from admin where id=4").executeUpdate();
// 关闭
con.close();
}
}

配置方式实现DBCP连接池,  配置文件中的key与BaseDataSouce中的属性一样:
db.properties
url=jdbc:mysql:///jdbc_demo
driverClassName=com.mysql.jdbc.Driver
username=root
password=root
initialSize=3
maxActive=6

方法4:C3P0连接池

C3P0连接池:

         最常用的连接池技术!Spring框架,默认支持C3P0连接池技术!

 

C3P0连接池,核心类:

CombopooledDataSource ds;

包名:com.mchange.v2.c3p0

类名:ClassComboPooledDataSource  implementsPooledDataSource implements DataSource

使用:

1.      下载,引入jar文件:  c3p0-0.9.1.2.jar

2.      使用连接池,创建连接

a)        硬编码方式

b)        配置方式(xml)

自动加载src下c3p0的配置文件【c3p0-config.xml】

public class App {

@Test
//1. 硬编码方式,使用C3P0连接池管理连接
public void testCode() throws Exception {
// 创建连接池核心工具类
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 设置连接参数:url、驱动、用户密码、初始连接数、最大连接数
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc_demo");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setInitialPoolSize(3);
dataSource.setMaxPoolSize(6);
dataSource.setMaxIdleTime(1000);

// ---> 从连接池对象中,获取连接对象
Connection con = dataSource.getConnection();
// 执行更新
con.prepareStatement("delete from admin where id=7").executeUpdate();
// 关闭
con.close();
}

@Test
//2. XML配置方式,使用C3P0连接池管理连接
public void testXML() throws Exception {
// 创建c3p0连接池核心工具类
// 自动加载src下c3p0的配置文件【c3p0-config.xml】
ComboPooledDataSource dataSource = new ComboPooledDataSource();// 使用默认的配置

// 获取连接
Connection con = dataSource.getConnection();
// 执行更新
con.prepareStatement("delete from admin where id=5").executeUpdate();
// 关闭
con.close();

}
}

总结:

DataSource 接口是 JDBC 2.0 API 中的新增内容,它提供了连接到数据源的另一种方法。使用 DataSource 对象是连接到数据源的首选方法。

 

DataSource比DriverManager好在哪里呢?

1. DataSource创建的connection既有基本实现,也有连接池实现(可以复用,DataSource帮我们实现了复用机制),而DriverManager创建的connection则不能复用(当然自己写连接池,自己来实现复用机制也是可以的,可以参考:使用动态代理实现自定义连接池)。所以sun公司规定连接池技术需要实现DataSource接口。

2. DataSource中封装了DriverManager的使用,使用DataSource的一个好处是可以在外边配置(如C3P0直接修改xml文件,不用自己写配置文件db.properties)。

3. 配置DataSource,由容器来获取Connection并结合连接池的应用比直接使用DriverManager操作JDBC效率高一些(参考:DBCP vs DriverManage效率)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: