两种数据库连接实现方式
第一种方式:DBCP
DBCP使用流程
- 导jar包
- 使用DBCP创建数据库连接对象
DataSource ds=BasicDataSourceFactory.createDatasource("一个存储连接信息的properties集合"); - 使用DataSource,调用连接池对象的getConnection方法
编写的.properties文件:dbcpconfig.properties
- #连接设置
- driverClassName=com.mysql.jdbc.Driver
- url=jdbc:mysql://localhost:3306/demobase
- username=root
- password=root
JDBCUtils中的代码:
- public class JDBCUtils {
-
- private static DataSource ds;
-
- static {
- try {
-
-
- InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
-
- Properties pro = new Properties();
- pro.load(in);
- ds = BasicDataSourceFactory.createDataSource(pro);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException();
- }
- }
-
- public static DataSource getDs(){
- return ds;
- }
- }
Test中的代码:
- public class Test {
- public static void main(String[] args) throws Exception {
- Connection con = JDBCUtils.getDs().getConnection();
-
- PreparedStatement ps = con.prepareStatement("select * from teacher");
- ResultSet rs = ps.executeQuery();
- while(rs.next()){
- System.out.println(rs.getString(1) + " " + rs.getString(2));
- }
-
- rs.close();
- ps.close();
-
- con.close();
- }
- }
第二种方式:C3P0
C3P0使用流程:
- 导jar包
- 使用C3P0创建对应的数据库连接对称
DataSource ds=new ComboPooledDataSource();
注意:
·虽然有配置文件,但是配置文件没有字节读取,c3p0会自动读取配置文件,此过程隐藏了;
·保存配置文件存在的路径在src中, 其实复制到bin目录下面了,真正读取是从bin目录下查找的;
·配置文件的文件名必须固定,即 c3p0-config.xml; - 具体的连接对象使用与DBCP一样
编写的XML文件:c3p0-config.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <c3p0-config>
- <!-- 默认配置,如果没有指定则使用这个配置
- 默认配置最常用
-
- 建议放在最开头。
- 放其他地方也没问题
- -->
- <default-config>
- <property name="driverClass">com.mysql.jdbc.Driver</property>
- <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/demobase</property>
- <property name="user">root</property>
- <property name="password">root</property>
- <property name="checkoutTimeout">30000</property>
- <property name="idleConnectionTestPeriod">30</property>
- <property name="initialPoolSize">10</property>
- <property name="maxIdleTime">30</property>
- <property name="maxPoolSize">100</property>
- <property name="minPoolSize">10</property>
- <property name="maxStatements">200</property>
- <user-overrides user="test-user">
- <property name="maxPoolSize">10</property>
- <property name="minPoolSize">1</property>
- <property name="maxStatements">0</property>
- </user-overrides>
- </default-config>
JDBCUtils中的代码:
- public class JDBCUtils {
-
- private static DataSource ds = new ComboPooledDataSource();
- public static DataSource ds(){
- return ds;
- }
- }
Test中的代码:
- public class Test {
- public static void main(String[] args) throws Exception {
- Connection con = JDBCUtils.ds().getConnection();
-
- PreparedStatement ps = con.prepareStatement("select * from teacher");
- ResultSet rs = ps.executeQuery();
- while(rs.next()){
- System.out.println(rs.getString(1) + " " + rs.getString(2));
- }
-
- rs.close();
- ps.close();
-
- con.close();
- }
- }