數據源(連接池)的作用
數據源(連接池)是提高程序性能如出現的
事先實例化數據源,初始化部分連接資源
使用連接資源時從數據源中獲取
使用完畢后將連接資源歸還給數據源
常見的數據源(連接池):DBCP、C3P0、BoneCP、Druid等
開發步驟
①導入數據源的坐標和數據庫驅動坐標
②創建數據源對象
③設置數據源的基本連接數據
④使用數據源獲取連接資源和歸還連接資源
數據源的手動創建
①導入c3p0
<!-- C3P0連接池 --><dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>
①導入mysql數據庫驅動坐標
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency>
②創建C3P0連接池
@Testpublic void testC3P0() throws Exception{ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/book?useSSL=false&serverTimezone=UTC");comboPooledDataSource.setUser("root");comboPooledDataSource.setPassword("123456");Connection connection=comboPooledDataSource.getConnection();System.out.println(connection);}
提取jdbc.properties配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/book?useSSL=false&serverTimezone=UTC
jdbc.username=xxx
jdbc.password=xxx
Spring配置數據源
可以將DataSource的創建權交由Spring容器去完成 DataSource有無參構造方法,而Spring默認就是通過無參構造方法實例化對象的
DataSource要想使用需要通過set方法設置數據庫連接信息,而Spring可以通過set方法進行字符串注入
@Testpublic void testC3P0() throws Exception{ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();ResourceBundle resourceBundle=ResourceBundle.getBundle("jdbc");comboPooledDataSource.setDriverClass(resourceBundle.getString("jdbc.driver"));comboPooledDataSource.setJdbcUrl(resourceBundle.getString("jdbc.url"));comboPooledDataSource.setUser(resourceBundle.getString("jdbc.username"));comboPooledDataSource.setPassword(resourceBundle.getString("jdbc.password"));Connection connection=comboPooledDataSource.getConnection();System.out.println(connection);}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<context:property-placeholder location="jdbc.properties"/><bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean></beans>
@Testpublic void testC3P02() throws Exception{ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");ComboPooledDataSource comboPooledDataSource=(ComboPooledDataSource) applicationContext.getBean("datasource");System.out.println(comboPooledDataSource.getConnection());}