數(shù)據(jù)庫連接池
連接池介紹
實際開發(fā)中“獲得連接”或“釋放資源”是非常消耗系統(tǒng)資源的兩個過程女仰,為了解決此類性能問題疾忍,通常情況我們采用連接池技術(shù),來共享連接 Connection一罩。這樣我們就不需要每次都創(chuàng)建連接撇簿、釋放連接了,因為這些操作都交給了連接池四瘫。
連接池的好處:使用池來管理 Connection汉嗽,這樣可以重復(fù)使用 Connection找蜜。當(dāng)使用完 Connection 后洗做,調(diào)用 Connection 的 close() 方法也不會真的關(guān)閉 Connection,而是把 Connection “歸還”給池畦徘。
如何使用數(shù)據(jù)庫連接池
Java 為數(shù)據(jù)庫連接池提供了公共的接口:javax.sql.DataSource影钉,各個廠商需要讓自己的連接池實現(xiàn)這個接口画髓,這樣應(yīng)用程序可以方便的切換不同廠商的連接池掘剪。
常見的連接池有 DBCP 連接池平委,C3P0 連接池,Druid 連接池夺谁。
數(shù)據(jù)準(zhǔn)備
在 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)置的連接池蜡塌。
1. 創(chuàng)建項目并導(dǎo)入 jar包
首先將 commons-dbcp 和 commons-pool 兩個 jar 包添加到 myJar 文件夾中,然后添加 myJar 庫到項目的依賴中勿负。
2.編寫工具類
連接數(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 = "123456";
// 創(chuàng)建連接池對象 (有 DBCP 提供的實現(xiàn)類)
public static BasicDataSource dataSource = new BasicDataSource();
// 使用靜態(tài)代碼塊進(jìn)行配置
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();
}
}
}
}
3. 測試工具類
/*
* 查詢所有員工的姓名
**/
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)擴(kuò)展锭硼。目前使用它的開源項目有 Hibernate房资、Spring 等。
1. 導(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>
<!--默認(rèn)配置-->
<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">123456</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>
2. 編寫 C3P0 工具類
C3P0 提供的核心工具類 ComboPooledDataSource颂郎,如果想使用連接池,就必須創(chuàng)建該類的對象容为。
使用默認(rèn)配置: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();
}
}
}
}
3. 測試工具類
// 查詢姓名為李白的記錄
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ù)庫連接池寺酪。在功能、性能替劈、擴(kuò)展性方面寄雀,都超過其他數(shù)據(jù)庫連接池,同時加入了日志監(jiān)控陨献,可以很好的監(jiān)控 DB 池連接和 SQL 的執(zhí)行情況盒犹。
1. 導(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=123456
initialSize=5
maxActive=10
maxWait=3000
2. 編寫 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();
}
}
}
}
3. 測試工具類
// 查詢薪資在 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);
}
}
DBUtils工具類
DBUtils簡介
Commons DbUtils 是 Apache 組織提供的一個對 JDBC 進(jìn)行簡單封裝的開源工具類庫晨雳,使用它能夠簡化 JDBC 應(yīng)用程序的開發(fā),同時也不會影響程序的性能奸腺。
DbUtils 就是 JDBC 的簡化開發(fā)工具包餐禁,需要在項目導(dǎo)入 commons-dbutils jar 包。
DbUtils 核心功能:
- QueryRunner 中提供對 SQL 語句操作的 API洋机。
- ResultSetHandler 接口用于定義 select 操作后封裝結(jié)果集坠宴。
- DbUtils 類是一個定義了關(guān)閉資源與事務(wù)處理相關(guān)方法的工具類。
表和類之間的關(guān)系:
整個表可以看做是一個類绷旗。
表中的一列喜鼓,對應(yīng)類中的一個成員屬性。
表中的一行記錄衔肢,對應(yīng)一個類的實例(對象)庄岖。
JavaBean 組件
JavaBean 是一個開發(fā)中通常用于封裝數(shù)據(jù)的類:
- 需要實現(xiàn)序列化接口,Serializable(暫時可以省略)
- 提供私有字段:private 類型變量名
- 提供 getter 和 setter
- 提供空參構(gòu)造
創(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
...
}
DBUtils完成 CRUD
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)增邦尊、刪背桐、改操作
步驟:
- 創(chuàng)建 QueryRunner(手動或自動)
- 占位符方式編寫SQL
- 設(shè)置占位符參數(shù)
- 執(zhí)行
添加:
@Test
public void testInsert() throws SQLException {
// 手動模式創(chuàng)建 QueryRunner
QueryRunner qr = new QueryRunner();
// 編寫占位符方式 SQL
String 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());
// 編寫 SQL
String 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é)果集進(jìn)行處理,達(dá)到一些業(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)建 QueryRunner
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
// 編寫 SQL
String 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)建QueryRunner
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
//2.編寫SQL
String 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);
}
數(shù)據(jù)庫批處理
什么是批處理
批處理操作數(shù)據(jù)庫:批處理指的是一次操作中執(zhí)行多條 SQL 語句熙参,批處理相比于一次一次執(zhí)行效率會提高很多。當(dāng)向數(shù)據(jù)庫中添加大量的數(shù)據(jù)時麦备,需要用到批處理孽椰。
實現(xiàn)批處理
Statement 和 PreparedStatement 都支持批處理操作。
MySQL 批處理是默認(rèn)關(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元數(shù)據(jù)
什么是元數(shù)據(jù)
除了表之外的數(shù)據(jù)都是元數(shù)據(jù)呛梆,可以分為三類:
- 查詢結(jié)果信息锐涯,UPDATE 或 DELETE語句 受影響的記錄數(shù)。
- 數(shù)據(jù)庫和數(shù)據(jù)表的信息填物,包含了數(shù)據(jù)庫及數(shù)據(jù)表的結(jié)構(gòu)信息纹腌。
- MySQL服務(wù)器信,包含了數(shù)據(jù)庫服務(wù)器的當(dāng)前狀態(tài)滞磺,版本號等升薯。
常用命令
select version(); 獲取 MySQL 服務(wù)器的版本信息
show status; 查看服務(wù)器的狀態(tài)信息
show columns from table_name; 顯示表的字段信息等,和 desc table_name 一樣
show index from table_name; 顯示數(shù)據(jù)表的詳細(xì)索引信息击困,包括主鍵
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)信息阅茶,或者蛛枚,使用程序查詢一個不熟悉的表時,可以通過獲取元素?fù)?jù)信息來了解表中有多少個字段脸哀、字段的名稱蹦浦、字段的類型。
DatabaseMetaData 描述數(shù)據(jù)庫的元數(shù)據(jù)對象
ResultSetMetaData 描述結(jié)果集的元數(shù)據(jù)對象
public class TestMetaData {
// 獲取數(shù)據(jù)庫相關(guān)的元數(shù)據(jù)信息
@Test
public 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ù)信息
@Test
public void testResultSetMetaData() throws SQLException {
Connection con = DruidUtils.getConnection();
PreparedStatement ps = con.prepareStatement("select * from employee");
ResultSet resultSet = ps.executeQuery();
// 獲取結(jié)果集元素?fù)?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);
}
}