mysql连接池_数据库技术:数据库连接池,Commons DbUtils,批处理,元数据
Database Connection Pool
Introduction to Database Connection Pool
實際開發(fā)中“獲得連接”或“釋放資源”是非常消耗系統(tǒng)資源的兩個過程,為了解決此類性能問題,通常情況我們采用連接池技術(shù),來共享連接 Connection。這樣我們就不需要每次都創(chuàng)建連接、釋放連接了,因為這些操作都交給了連接池。
連接池的好處:使用池來管理 Connection,這樣可以重復(fù)使用 Connection。當(dāng)使用完 Connection 后,調(diào)用 Connection 的 close() 方法也不會真的關(guān)閉 Connection,而是把 Connection “歸還”給池。
How to Use Database Connection Pool?
Java 為數(shù)據(jù)庫連接池提供了公共的接口:javax.sql.DataSource,各個廠商需要讓自己的連接池實現(xiàn)這個接口,這樣應(yīng)用程序可以方便的切換不同廠商的連接池。
常見的連接池有 DBCP 連接池,C3P0 連接池,Druid 連接池。
想了解更多,歡迎關(guān)注我的微信公眾號:Renda_ZhangData Preparation
在 MySQL 中準(zhǔn)備好以下數(shù)據(jù)
# 創(chuàng)建數(shù)據(jù)庫 CREATE DATABASE db5 CHARACTER SET utf8;# 使用數(shù)據(jù)庫 USE db5;# 創(chuàng)建員工表 CREATE TABLE employee (eid INT PRIMARY KEY AUTO_INCREMENT,ename VARCHAR (20), -- 員工姓名age INT, -- 員工年齡sex VARCHAR (6), -- 員工性別salary DOUBLE, -- 薪水empdate DATE -- 入職日期 );# 插入數(shù)據(jù) INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'李清照',22,'女',4000,'2018-11-12'); INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'林黛玉',20,'女',5000,'2019-03-14'); INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'杜甫',40,'男',6000,'2020-01-01'); INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'李白',25,'男',3000,'2017-10-01');DBCP 連接池
DBCP 是一個開源的連接池,是 Apache 成員之一,在企業(yè)開發(fā)中比較常見,Tomcat 內(nèi)置的連接池。
創(chuàng)建項目并導(dǎo)入 jar包
首先將 commons-dbcp 和 commons-pool 兩個 jar 包添加到 myJar 文件夾中,然后添加 myJar 庫到項目的依賴中。
編寫工具類
連接數(shù)據(jù)庫表的工具類,采用 DBCP 連接池的方式來完成。
在 DBCP 包中提供了 DataSource 接口的實現(xiàn)類,我們要用的具體的連接池 BasicDataSource 類。
public class DBCPUtils {// 定義常量 保存數(shù)據(jù)庫連接的相關(guān)信息public static final String DRIVERNAME = "com.mysql.jdbc.Driver";public static final String URL = "jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8";public static final String USERNAME = "root";public static final String PASSWORD = "root";// 創(chuàng)建連接池對象 (有 DBCP 提供的實現(xiàn)類)public static BasicDataSource dataSource = new BasicDataSource();// 使用靜態(tài)代碼塊進行配置static{dataSource.setDriverClassName(DRIVERNAME);dataSource.setUrl(URL);dataSource.setUsername(USERNAME);dataSource.setPassword(PASSWORD);}// 獲取連接的方法public static Connection getConnection() throws SQLException {// 從連接池中獲取連接Connection connection = dataSource.getConnection();return connection;}// 釋放資源方法public static void close(Connection con, Statement statement){if(con != null && statement != null){try {statement.close();// 歸還連接con.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(Connection con, Statement statement, ResultSet resultSet){if(con != null && statement != null && resultSet != null){try {resultSet.close();statement.close();// 歸還連接con.close();} catch (SQLException e) {e.printStackTrace();}}} }測試工具類
/** 查詢所有員工的姓名**/ public class TestDBCP {public static void main(String[] args) throws SQLException {// 從 DBCP 連接池中拿到連接Connection con = DBCPUtils.getConnection();// 獲取 Statement 對象Statement statement = con.createStatement();// 查詢所有員工的姓名String sql = "select ename from employee";ResultSet resultSet = statement.executeQuery(sql);// 處理結(jié)果集while(resultSet.next()){String ename = resultSet.getString("ename");System.out.println("員工姓名: " + ename);}// 釋放資源DBCPUtils.close(con, statement, resultSet);} }C3P0 連接池
C3P0 是一個開源的 JDBC 連接池,支持 JDBC 3 規(guī)范和 JDBC 2 的標(biāo)準(zhǔn)擴展。目前使用它的開源項目有 Hibernate、Spring 等。
導(dǎo)入 jar 包及配置文件
首先將 c3p0 和 mchange-commons-java 兩個 jar 包復(fù)制到 myJar 文件夾即可,IDEA 會自動導(dǎo)入。
然后導(dǎo)入配置文件 c3p0-con?g.xml。c3p0-con?g.xml 文件名不可更改,可以直接放到 src 下,也可以放到到資源文件夾中。
最后在項目下創(chuàng)建一個 resource 文件夾(專門存放資源文件),將配置文件放在 resource 目錄下即可,創(chuàng)建連接池對象的時候會自動加載這個配置文件。
<c3p0-config><!--默認配置--><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8</property><property name="user">root</property><property name="password">root</property><!-- initialPoolSize:初始化時獲取三個連接,取值在 minPoolSize 與 maxPoolSize 之間。--><property name="initialPoolSize">3</property><!-- maxIdleTime:最大空閑時間,60 秒內(nèi)未使用則連接被丟棄。若為 0 則永不丟棄。--><property name="maxIdleTime">60</property><!-- maxPoolSize:連接池中保留的最大連接數(shù) --><property name="maxPoolSize">100</property><!-- minPoolSize: 連接池中保留的最小連接數(shù) --><property name="minPoolSize">10</property></default-config><!--配置連接池 mysql--><named-config name="mysql"><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/db5</property><property name="user">root</property><property name="password">root</property><property name="initialPoolSize">10</property><property name="maxIdleTime">30</property><property name="maxPoolSize">100</property><property name="minPoolSize">10</property></named-config><!--可以配置多個連接池--></c3p0-config>編寫 C3P0 工具類
C3P0 提供的核心工具類 ComboPooledDataSource,如果想使用連接池,就必須創(chuàng)建該類的對象。
使用默認配置:new ComboPooledDataSource();
使用命名配置:new ComboPooledDataSource("mysql");
public class C3P0Utils {// 使用指定的配置public static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");// 獲取連接的方法public static Connection getConnection() throws SQLException {return dataSource.getConnection();}// 釋放資源public static void close(Connection con, Statement statement){if(con != null && statement != null){try {statement.close();// 歸還連接con.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(Connection con, Statement statement, ResultSet resultSet){if(con != null && statement != null && resultSet != null){try {resultSet.close();statement.close();// 歸還連接con.close();} catch (SQLException e) {e.printStackTrace();}}} }測試工具類
// 查詢姓名為李白的記錄 public class TestC3P0 {public static void main(String[] args) throws SQLException {// 獲取連接Connection con = C3P0Utils.getConnection();// 獲取預(yù)處理對象String sql = "select * from employee where ename = ?";PreparedStatement ps = con.prepareStatement(sql);// 設(shè)置占位符的值ps.setString(1,"李白");ResultSet resultSet = ps.executeQuery();// 處理結(jié)果集while (resultSet.next()){int eid = resultSet.getInt("eid");String ename = resultSet.getString("ename");int age = resultSet.getInt("age");String sex = resultSet.getString("sex");double salary = resultSet.getDouble("salary");Date date = resultSet.getDate("empdate");System.out.println(eid+" "+ename+" "+age+" "+sex+" "+salary+" "+date);}// 釋放資源C3P0Utils.close(con, ps, resultSet);} }Druid 連接池
Druid(德魯伊)是阿里巴巴開發(fā)的為監(jiān)控而生的數(shù)據(jù)庫連接池,Druid 是目前最好的數(shù)據(jù)庫連接池。在功能、性能、擴展性方面,都超過其他數(shù)據(jù)庫連接池,同時加入了日志監(jiān)控,可以很好的監(jiān)控 DB 池連接和 SQL 的執(zhí)行情況。
導(dǎo)入 jar 包及配置文件
首先導(dǎo)入 druid jar 包。然后導(dǎo)入 properties 配置文件,可以叫任意名稱,可以放在任意目錄下,但是這里統(tǒng)一放到 resources 資源目錄。
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8 username=root password=root initialSize=5 maxActive=10 maxWait=3000編寫 Druid 工具類
通過工廠來來獲取 DruidDataSourceFactory 類的 createDataSource(Properties p) 方法,其參數(shù)可以是一個屬性集對象。
public class DruidUtils {// 定義成員變量public static DataSource dataSource;// 靜態(tài)代碼塊static{try {// 創(chuàng)建屬性集對象Properties p = new Properties();// 加載配置文件 Druid 連接池不能夠主動加載配置文件,需要指定文件InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");// 使用 Properties 對象的 load 方法從字節(jié)流中讀取配置信息p.load(inputStream);// 通過工廠類獲取連接池對象dataSource = DruidDataSourceFactory.createDataSource(p);} catch (Exception e) {e.printStackTrace();}}// 獲取連接的方法public static Connection getConnection(){try {return dataSource.getConnection();} catch (SQLException e) {e.printStackTrace();return null;}}// 釋放資源public static void close(Connection con, Statement statement){if(con != null && statement != null){try {statement.close();// 歸還連接con.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(Connection con, Statement statement, ResultSet resultSet){if(con != null && statement != null && resultSet != null){try {resultSet.close();statement.close();// 歸還連接con.close();} catch (SQLException e) {e.printStackTrace();}}} }測試工具類
// 查詢薪資在 3000 - 5000 元之間的員工姓名 public class TestDruid {public static void main(String[] args) throws SQLException {// 獲取連接Connection con = DruidUtils.getConnection();// 獲取 Statement 對象Statement statement = con.createStatement();// 執(zhí)行查詢ResultSet resultSet = statement.executeQuery("select ename from employee where salary between 3000 and 5000");// 處理結(jié)果集while(resultSet.next()){String ename = resultSet.getString("ename");System.out.println(ename);}// 釋放資源DruidUtils.close(con,statement,resultSet);} }Commons DbUtils
Introduction to DbUtils
Commons DbUtils 是 Apache 組織提供的一個對 JDBC 進行簡單封裝的開源工具類庫,使用它能夠簡化 JDBC 應(yīng)用程序的開發(fā),同時也不會影響程序的性能。
DbUtils 就是 JDBC 的簡化開發(fā)工具包,需要在項目導(dǎo)入 commons-dbutils jar 包。
DbUtils 核心功能:
相關(guān)知識
表和類之間的關(guān)系
整個表可以看做是一個類。
表中的一列,對應(yīng)類中的一個成員屬性。
表中的一行記錄,對應(yīng)一個類的實例(對象)。
JavaBean 組件
JavaBean 是一個開發(fā)中通常用于封裝數(shù)據(jù)的類:
創(chuàng)建一個 entity 包,專門用來存放 JavaBean 類,然后在 entity 包中創(chuàng)建一個和數(shù)據(jù)庫的 Employee 表對應(yīng)的 Employee 類。
public class Employee implements Serializable {private int eid;private String ename;private int age;private String sex;private double salary;private Date empdate;// getter setter... }Use DbUtils for CRUD Operations
QueryRunner 的創(chuàng)建
手動模式
// 創(chuàng)建 QueryRunner 對象 QueryRunner qr = new QueryRunner();自動模式
// 傳入數(shù)據(jù)庫連接池對象 QueryRunner qr2 = new QueryRunner(DruidUtils.getDataSource());自動模式需要傳入連接池對象
// 獲取連接池對象 public static DataSource getDataSource(){return dataSource; }QueryRunner 實現(xiàn)增、刪、改操作
步驟:
添加:
@Test public void testInsert() throws SQLException {// 手動模式創(chuàng)建 QueryRunnerQueryRunner qr = new QueryRunner();// 編寫占位符方式 SQLString sql = "insert into employee values(?,?,?,?,?,?)";// 設(shè)置占位符的參數(shù)Object[] param = {null,"布萊爾",20,"女",10000,"1990-12-26"};// 執(zhí)行 update 方法Connection con = DruidUtils.getConnection();int i = qr.update(con, sql, param);// 釋放資源DbUtils.closeQuietly(con); }修改:
@Test public void testUpdate() throws SQLException {// 自動模式創(chuàng)建 QueryRunner 對象,傳入數(shù)據(jù)庫連接池QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());// 編寫 SQLString sql = "update employee set salary = ? where ename = ?";// 設(shè)置占位符參數(shù)Object[] param = {0, "布萊爾"};// 執(zhí)行 update,不需要傳入連接對象qr.update(sql, param); }刪除:
@Test public void testDelete() throws SQLException {QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());String sql = "delete from employee where eid = ?";//只有一個參數(shù),不需要創(chuàng)建數(shù)組qr.update(sql, 1); }QueryRunner 實現(xiàn)查詢操作
ResultSetHandler 可以對查詢出來的 ResultSet 結(jié)果集進行處理,達到一些業(yè)務(wù)上的需求。
query 方法的返回值都是泛型,具體的返回值類型會根據(jù)結(jié)果集的處理方式發(fā)生變化。
query(String sql, ResultSetHandler rsh, Object[] param) -- 自動模式創(chuàng)建QueryRunner, 執(zhí)行查詢。
query(Connection con, String sql, ResultSetHandler rsh, Object[] param) -- 手動模式創(chuàng)建 QueryRunner, 執(zhí)行查詢。
/** 查詢 id 為 5 的記錄,封裝到數(shù)組中** ArrayHandler:* 將結(jié)果集的第一條數(shù)據(jù)封裝到 Object[] 數(shù)組中,* 數(shù)組中的每一個元素就是這條記錄中的每一個字段的值**/ @Test public void testFindById() throws SQLException {// 創(chuàng)建 QueryRunnerQueryRunner qr = new QueryRunner(DruidUtils.getDataSource());// 編寫 SQLString sql = "select * from employee where eid = ?";// 執(zhí)行查詢Object[] query = qr.query(sql, new ArrayHandler(), 5);// 獲取數(shù)據(jù)System.out.println(Arrays.toString(query)); } /*** 查詢所有數(shù)據(jù),封裝到 List 集合中** ArrayListHandler:* 可以將每條數(shù)據(jù)先封裝到 Object[] 數(shù)組中,* 再將數(shù)組封裝到集合中*/ @Test public void testFindAll() throws SQLException {//1.創(chuàng)建QueryRunnerQueryRunner qr = new QueryRunner(DruidUtils.getDataSource());//2.編寫SQLString sql = "select * from employee";//3.執(zhí)行查詢List<Object[]> query = qr.query(sql, new ArrayListHandler());//4.遍歷集合獲取數(shù)據(jù)for (Object[] objects : query) {System.out.println(Arrays.toString(objects));} } /*** 查詢 id 為 3 的記錄,封裝到指定 JavaBean 中** BeanHandler:* 將結(jié)果集的第一條數(shù)據(jù)封裝到 JavaBean 中**/ @Test public void testFindByIdJavaBean() throws SQLException {QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());String sql = "select * from employee where eid = ?";Employee employee = qr.query(sql, new BeanHandler<Employee>(Employee.class), 3);System.out.println(employee); } /** 查詢薪資大于 3000 的所員工信息,* 封裝到 JavaBean 中再封裝到 List 集合中** BeanListHandler:* 將結(jié)果集的每一條和數(shù)據(jù)封裝到 JavaBean 中,* 再將 JavaBean 放到 List 集合中* */ @Test public void testFindBySalary() throws SQLException {QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());String sql = "select * from employee where salary > ?";List<Employee> list = qr.query(sql, new BeanListHandler<Employee>(Employee.class), 3000);for (Employee employee : list) {System.out.println(employee);} } /** 查詢姓名是布萊爾的員工信息,* 將結(jié)果封裝到 Map 集合中** MapHandler:* 將結(jié)果集的第一條記錄封裝到 Map 中,* key 對應(yīng)的是列名,* value 對應(yīng)的是列的值**/ @Test public void testFindByName() throws SQLException {QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());String sql = "select * from employee where ename = ?";Map<String, Object> map = qr.query(sql, new MapHandler(), "布萊爾");Set<Map.Entry<String, Object>> entries = map.entrySet();for (Map.Entry<String, Object> entry : entries) {System.out.println(entry.getKey() +" = " +entry.getValue());} } /** 查詢所有員工的薪資總額** ScalarHandler:* 用于封裝單個的數(shù)據(jù)**/ @Test public void testGetSum() throws SQLException {QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());String sql = "select sum(salary) from employee";Double sum = (Double) qr.query(sql, new ScalarHandler<>());System.out.println("員工薪資總額: " + sum); }Database Batch Process
What is Database Batch Process?
批處理操作數(shù)據(jù)庫:批處理指的是一次操作中執(zhí)行多條 SQL 語句,批處理相比于一次一次執(zhí)行效率會提高很多。當(dāng)向數(shù)據(jù)庫中添加大量的數(shù)據(jù)時,需要用到批處理。
Implement Batch Processing
Statement 和 PreparedStatement 都支持批處理操作。
MySQL 批處理是默認關(guān)閉的,所以需要加一個參數(shù)才打開 MySQL 數(shù)據(jù)庫批處理,在 url 中添加 rewriteBatchedStatements=true。
url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8&rewriteBatchedStatements=true創(chuàng)建一張表
CREATE TABLE testBatch (id INT PRIMARY KEY AUTO_INCREMENT,uname VARCHAR(50) )測試向表中插入一萬條數(shù)據(jù)
public class TestBatch {public static void main(String[] args) {try {// 獲取連接Connection con = DruidUtils.getConnection();// 獲取預(yù)處理對象String sql ="insert into testBatch(uname) values(?)";PreparedStatement ps = con.prepareStatement(sql);// 創(chuàng)建 for 循環(huán)來設(shè)置占位符參數(shù)for (int i = 0; i < 10000 ; i++) {ps.setString(1, "小明"+i);// 將 SQL 添加到批處理列表ps.addBatch();}long start = System.currentTimeMillis();// 統(tǒng)一批量執(zhí)行ps.executeBatch();long end = System.currentTimeMillis();System.out.println("插入10000條數(shù)據(jù)使用: "+(end-start)+" 毫秒!");} catch (SQLException e) {e.printStackTrace();}} }MySQL Metadata
What is Metadata in MySQL
除了表之外的數(shù)據(jù)都是元數(shù)據(jù),可以分為三類:
常用命令
select version(); 獲取 MySQL 服務(wù)器的版本信息
show status; 查看服務(wù)器的狀態(tài)信息
show columns from table_name; 顯示表的字段信息等,和 desc table_name 一樣
show index from table_name; 顯示數(shù)據(jù)表的詳細索引信息,包括主鍵
show databases: 列出所有數(shù)據(jù)庫
show tables; 顯示當(dāng)前數(shù)據(jù)庫的所有表
select database(); 獲取當(dāng)前的數(shù)據(jù)庫名
使用 JDBC 獲取元數(shù)據(jù)
通過 JDBC 也可以獲取到元數(shù)據(jù),比如,數(shù)據(jù)庫的相關(guān)信息,或者,使用程序查詢一個不熟悉的表時,可以通過獲取元素據(jù)信息來了解表中有多少個字段、字段的名稱、字段的類型。
DatabaseMetaData 描述數(shù)據(jù)庫的元數(shù)據(jù)對象
ResultSetMetaData 描述結(jié)果集的元數(shù)據(jù)對象
public class TestMetaData {// 獲取數(shù)據(jù)庫相關(guān)的元數(shù)據(jù)信息@Testpublic void testDataBaseMetaData() throws SQLException {Connection connection = DruidUtils.getConnection();// 獲取代表數(shù)據(jù)庫的元數(shù)據(jù)對象DatabaseMetaData metaData = connection.getMetaData();// 獲取數(shù)據(jù)庫相關(guān)的元數(shù)據(jù)信息String url = metaData.getURL();System.out.println("數(shù)據(jù)庫URL: " + url);String userName = metaData.getUserName();System.out.println("當(dāng)前用戶: " + userName );String productName = metaData.getDatabaseProductName();System.out.println("數(shù)據(jù)庫產(chǎn)品名: " + productName);String version = metaData.getDatabaseProductVersion();System.out.println("數(shù)據(jù)庫版本: " + version);String driverName = metaData.getDriverName();System.out.println("驅(qū)動名稱: " + driverName);// 判斷當(dāng)前數(shù)據(jù)庫是否只允許只讀boolean b = metaData.isReadOnly();if(b){System.out.println("當(dāng)前數(shù)據(jù)庫只允許讀操作!");}else{System.out.println("不是只讀數(shù)據(jù)庫");}connection.close();}// 獲取結(jié)果集中的元數(shù)據(jù)信息@Testpublic void testResultSetMetaData() throws SQLException {Connection con = DruidUtils.getConnection();PreparedStatement ps = con.prepareStatement("select * from employee");ResultSet resultSet = ps.executeQuery();// 獲取結(jié)果集元素據(jù)對象ResultSetMetaData metaData = ps.getMetaData();// 獲取當(dāng)前結(jié)果集共有多少列int count = metaData.getColumnCount();System.out.println("當(dāng)前結(jié)果集中共有: "+count+"列");// 獲結(jié)果集中列的名稱和類型for (int i = 1; i <= count; i++) {String columnName = metaData.getColumnName(i);System.out.println("列名: "+columnName);String columnTypeName = metaData.getColumnTypeName(i);System.out.println("類型: "+columnTypeName);}DruidUtils.close(con, ps, resultSet);} }總結(jié)
以上是生活随笔為你收集整理的mysql连接池_数据库技术:数据库连接池,Commons DbUtils,批处理,元数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 十九、PHP框架Laravel学习笔记—
- 下一篇: MongoDB 数据库创建、删除、表(集