Java数据库连接池

Java数据库连接池,第1张

Java数据库连接

概念:是一个容器(在Java中就是一个集合),存放数据库连接的容器。当系统初始化好之后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。

不像之前的代码一样,每次开始前都建立一个连接,然后结束时close,释放连接。

好处:节约资源、高效。

实现:
标准接口:DataSource javax.sql包下的。获取连接getConnection方法.调用Connection.close()方法,就实现了归还连接到连接池。
一般由数据库厂商来实现。
两种数据库连接池实现技术C3P0、Druid。

C3P0

使用步骤:
1、导入jar包。有两个jar包,均需要导入。

2、需要定义配置文件 文件名为c3p0.properties或者c3p0-config.xml。目录为src。
3、创建核心对象 数据库连接池对象 ComboPooledDataSource。
4、获取连接getConnection

注意:不要忘记导入数据库的驱动jar包


    
    
        com.mysql.jdbc.Driver
        
            
        
        root
        123456
        
        2
        
        30
        
        10
        
        2
        
        50
    
    
    
        com.mysql.jdbc.Driver
        jdbc:mysql://127.0.0.1:3306/demo
        root
        123456
        5
        100
        50
        1000
        0
        5 
    

有多个配置,分别是默认配置和命名配置。

package com.itcast.dataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class c3p0_demo1 {
    public static void main(String[] args) {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

"C:Program FilesJavajdk1.8.0_221binjava.exe" "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA 2021.2libidea_rt.jar=53849:C:Program FilesJetBrainsIntelliJ IDEA 2021.2bin" -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_221jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_221jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_221jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_221jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_221jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_221jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_221jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_221jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_221jrelibextnashorn.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_221jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_221jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_221jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_221jrelibjce.jar;C:Program FilesJavajdk1.8.0_221jrelibjfr.jar;C:Program FilesJavajdk1.8.0_221jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_221jrelibjsse.jar;C:Program FilesJavajdk1.8.0_221jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_221jrelibplugin.jar;C:Program FilesJavajdk1.8.0_221jrelibresources.jar;C:Program FilesJavajdk1.8.0_221jrelibrt.jar;E:java 学习代码my_jdbcoutproductionmy_jdbc;E:java 学习代码my_jdbclibsmysql-connector-java-5.1.48.jar;E:java 学习代码my_jdbclibsmchange-commons-java-0.2.3.4.jar;E:java 学习代码my_jdbclibsc3p0-0.9.2.1.jar;D:repositoryjunitjunit4.13.1junit-4.13.1.jar;D:repositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar" com.itcast.dataSource.c3p0_demo1
二月 05, 2022 10:41:44 上午 com.mchange.v2.log.MLog 
信息: MLog clients using java 1.4+ standard logging.
二月 05, 2022 10:41:45 上午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]
二月 05, 2022 10:41:45 上午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitonClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge1elam1jfc32k17mzvgj|7eda2dbb, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge1elam1jfc32k17mzvgj|7eda2dbb, idleConnectionTestPeriod -> 0, initialPoolSize -> 2, jdbcUrl -> jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 30, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 2, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
com.mchange.v2.c3p0.impl.NewProxyConnection@2f410acf

Process finished with exit code 0
druid使用

使用步骤:
1、导入jar包 除了有druid还有mysql的
2、定义配置文件 properties形式的 druid.properties。可以叫任意名称,可以放置在任意的目录下。手动加载。

driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/demo
username = root
password = 123456
initialSize = 5
maxActive = 10
maxWait = 3000

3、获取数据库连接池对象 通过工厂类来获取 DruidDataSourceFactory
4、获取连接 getConnection

package com.itcast.dataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class druid_demo1 {
    public static void main(String[] args)throws Exception {
        //加载配置文件
        Properties properties = new Properties();
        InputStream inputStream = druid_demo1.class.getClassLoader().getResourceAsStream("druid.properties");
        properties.load(inputStream);
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}
二月 05, 2022 11:03:07 上午 com.alibaba.druid.pool.DruidDataSource info
信息: {dataSource-1} inited
com.mysql.jdbc.JDBC4Connection@7bfcd12c

Process finished with exit code 0
连接池工具类

一般情况下,还是使用工具类JDBCUtils
方法:获取连接的方法 释放资源 获取连接池的方法
提供静态代码块加载配置文件,初始化连接池对象

package com.itcast.dataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

//连接池工具类
public class JDBCUtils {
    private static DataSource ds;
    static {
        try {
            Properties properties = new Properties();
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
            try {
                ds = DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接方法
    public static Connection  getConnection() throws Exception{
        return ds.getConnection();
    }
    //释放资源方法 方法的重载
    public static void close(Statement stmt, Connection conn){
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //方法的重载
    public static void close(Statement stmt, Connection conn, ResultSet res){
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (res != null){
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //获取连接池的方法
    public static DataSource getDatasource(){
        return ds;
    }
}
package com.itcast.dataSource;

import java.sql.Connection;
import java.sql.Statement;

public class druid_JDBCUtils {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();
            String sql = "insert into actor values(null,'Amy','女','1999-9-15','550')";
            int i = statement.executeUpdate(sql);
            if (i>0){
                System.out.println("执行成功");
            }else {
                System.out.println("执行失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(statement,connection);
        }
    }
}
二月 05, 2022 4:54:29 下午 com.alibaba.druid.pool.DruidDataSource info
信息: {dataSource-1} inited
执行成功

Process finished with exit code 0

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5721578.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存