新聞中心
JDBC是Java Database Connectivity的縮寫,即Java數(shù)據(jù)庫連接,是Java的一個標準的接口,定義了一套標準的訪問數(shù)據(jù)庫的接口。JDBC提供了一種基于SQL語句進行數(shù)據(jù)庫操作的方式,使得Java程序能夠訪問各種類型的數(shù)據(jù)庫。

JDBC連接數(shù)據(jù)庫是Java開發(fā)中必不可少的一部分,但是每次使用JDBC連接數(shù)據(jù)庫時都需要手動編寫大量的重復代碼,這不僅繁瑣而且容易出錯。因此,我們通常會將數(shù)據(jù)庫的連接和操作封裝起來,以減少代碼的重復性,提高代碼的重用性和可維護性。接下來,本文將介紹jdbc連接數(shù)據(jù)庫封裝實現(xiàn)方法的詳細步驟。
實現(xiàn)步驟
1、定義一個數(shù)據(jù)庫連接池類
為了封裝數(shù)據(jù)庫連接,我們需要定義一個連接池類,用于維護數(shù)據(jù)庫連接。在該類中,我們需要定義一個數(shù)據(jù)庫連接池的列表(List)和一個線程池(ExecutorService),在連接池初始化時,我們需要向連接池添加指定數(shù)量的數(shù)據(jù)庫連接,同時創(chuàng)建一個線程池用于管理數(shù)據(jù)庫連接的釋放。連接池類的代碼如下:
“`java
public class ConnectionPool {
private List pool;
private static final int DEFAULT_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int TIMEOUT = 5000;
private ConnectionPool() {
pool = new ArrayList(DEFAULT_POOL_SIZE);
for (int i = 0; i
pool.add(createConnection());
}
}
public static ConnectionPool getInstance() {
return ConnectionPoolHolder.INSTANCE;
}
private static class ConnectionPoolHolder {
private static final ConnectionPool INSTANCE = new ConnectionPool();
}
public synchronized Connection getConnection() {
int index = pool.size() – 1;
Connection connection = pool.remove(index);
try {
if (connection.isClosed()) {
connection = getConnection();
}
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
connection = getConnection();
}
return connection;
}
public synchronized void releaseConnection(Connection connection) {
if (pool.size() >= MAX_POOL_SIZE) {
try {
connection.close();
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
} else {
pool.add(connection);
}
}
private Connection createConnection() {
Connection connection = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
String url = “jdbc:mysql://localhost:3306/test”;
String user = “root”;
String password = “123456”;
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
return connection;
}
public void closePool() {
for (Connection connection : pool) {
try {
connection.close();
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
}
pool.clear();
}
}
“`
在該類中,我們使用了單例模式來保證全局只有一個ConnectionPool對象。在getConnection()方法中,我們從連接池中獲取一個數(shù)據(jù)庫連接,若該連接已關閉,則嘗試從池中獲取另一個連接;在releaseConnection()方法中,我們將數(shù)據(jù)庫連接釋放回連接池供其他線程使用;在createConnection()方法中,我們使用DriverManager獲取一個數(shù)據(jù)庫連接。
2、定義一個數(shù)據(jù)庫操作類
除了連接池類之外,我們還需要定義一個數(shù)據(jù)庫操作類,用于執(zhí)行各種SQL語句。在該類中,我們需要定義一個ConnectionPool對象以獲取數(shù)據(jù)庫連接,同時定義一系列的執(zhí)行SQL語句的方法。數(shù)據(jù)庫操作類的代碼如下:
“`java
public class DBHelper {
private ConnectionPool connectionPool;
public DBHelper() {
connectionPool = ConnectionPool.getInstance();
}
public ResultSet executeQuery(String sql) {
ResultSet resultSet = null;
try (Connection connection = connectionPool.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
resultSet = statement.executeQuery();
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
return resultSet;
}
public int executeUpdate(String sql) {
int rowsUpdated = 0;
try (Connection connection = connectionPool.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
rowsUpdated = statement.executeUpdate();
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
return rowsUpdated;
}
public int executeUpdate(String sql, List params) {
int rowsUpdated = 0;
try (Connection connection = connectionPool.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
int index = 1;
for (Object obj : params) {
statement.setObject(index, obj);
index++;
}
rowsUpdated = statement.executeUpdate();
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
return rowsUpdated;
}
}
“`
在該類中,我們使用了try-with-resources語句來自動關閉資源。executeQuery()方法用于執(zhí)行SELECT語句,并返回一個ResultSet對象;executeUpdate()方法用于執(zhí)行INSERT、UPDATE、DELETE語句,并返回受影響的行數(shù);executeUpdate()方法還提供了一個可變參數(shù)的params列表,用于設置PreparedStatement中的參數(shù)。
3、測試連接池和數(shù)據(jù)庫操作類
在完成了連接池和數(shù)據(jù)庫操作類的定義之后,我們需要對其進行測試。在測試之前,我們需要在數(shù)據(jù)庫中創(chuàng)建一個名為”test”的數(shù)據(jù)庫,并在該數(shù)據(jù)庫中創(chuàng)建一個名為”users”的表,其結(jié)構(gòu)如下:
“`sql
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
“`
在測試類中,我們需要通過DBHelper對象來執(zhí)行各種SQL語句(查詢、插入等),同時需要手動釋放資源。測試代碼如下:
“`java
public class TestJDBC {
public static void mn(String[] args) {
testConnectionPool();
testDBHelper();
}
private static void testConnectionPool() {
ConnectionPool connectionPool = ConnectionPool.getInstance();
for (int i = 0; i
Connection connection = connectionPool.getConnection();
if (connection != null) {
System.out.println(“Success: ” + connection);
} else {
System.out.println(“Fl: ” + i + “, ” + connection);
}
}
connectionPool.closePool();
}
private static void testDBHelper() {
DBHelper dbHelper = new DBHelper();
// insert
String sql = “INSERT INTO `users`(`name`, `age`) VALUES (‘Tom’, 20)”;
int rowsUpdated = dbHelper.executeUpdate(sql);
System.out.println(“Rows updated: ” + rowsUpdated);
// insert with parameters
sql = “INSERT INTO `users`(`name`, `age`) VALUES (?, ?)”;
List params = new ArrayList();
params.add(“Jerry”);
params.add(22);
rowsUpdated = dbHelper.executeUpdate(sql, params);
System.out.println(“Rows updated: ” + rowsUpdated);
// select
sql = “SELECT * FROM `users`”;
ResultSet resultSet = dbHelper.executeQuery(sql);
try {
while (resultSet.next()) {
System.out.println(“ID: ” + resultSet.getInt(“id”)
+ “, Name: ” + resultSet.getString(“name”)
+ “, Age: ” + resultSet.getInt(“age”));
}
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
System.out.println(“Error: ” + e.getMessage());
}
}
}
“`
在測試代碼中,我們首先通過testConnectionPool()方法測試連接池的功能,可以看到在連接池已滿的情況下,getConnection()方法會返回null。然后我們通過testDBHelper()方法測試DBHelper類的功能,可以看到在執(zhí)行各種SQL語句時,我們不需要手動獲取和釋放數(shù)據(jù)庫連接,這些操作已經(jīng)被封裝在DBHelper類的方法中了。
相關問題拓展閱讀:
- java 使用jdbc技術(shù)怎樣連接同一個數(shù)據(jù)庫,但有多個數(shù)據(jù)庫名?
java 使用jdbc技術(shù)怎樣連接同一個數(shù)據(jù)庫,但有多個數(shù)據(jù)庫名?
將連接封搭埋裝起來 一個工廠類
public class ConnectionFactory {
private static String _url = null;
private static String _user = null;
private static String _pwd = null;
private static String _driver = null;
public ConnectionFactory() {
// TODO Auto-generated constructor stub
}
static {
_driver = DBConfig.getDBConfig().getValue(“driver”);
_user = DBConfig.getDBConfig().getValue(“user”);
_pwd = DBConfig.getDBConfig().getValue(“password”);
_url = DBConfig.getDBConfig().getValue(“url”);
}
public static Connection getConnection() throws SQLException {
try {
Class.forName(_driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(“注冊驅(qū)動失敗”);
e.printStackTrace();
throw new SQLException(“注冊鍵租驅(qū)動失敗”);
}
return DriverManager.getConnection(_url, _user, _pwd);
}
public static void release(Connection con, Statement stm, ResultSet rs) {
try {
if (con != null) {
con.close();
}
if (stm != null) {
con.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
然后再寫一個配置文稿枝兆件
public class DBConfig {
private static DBConfig instance;
private static Properties info = new Properties();
private static String path = “dbconfig.properties”;
public DBConfig() {
// TODO Auto-generated constructor stub
readDBConfig();
}
private void readDBConfig() {
InputStream inputStream = null;
try {
if (!(new File(path).exists())) {
path = “./bin/” + path;
}
inputStream = new FileInputStream(path);
info.load(inputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public synchronized static DBConfig getDBConfig() {
// 注意這里
if (instance == null) {
instance = new DBConfig();
}
return instance;
}
public String getValue(String key) {
return info.getProperty(key);
}
public static void main(String args) {
String driver = DBConfig.getDBConfig().getValue(“driver”);
String user = DBConfig.getDBConfig().getValue(“user”);
String pwd = DBConfig.getDBConfig().getValue(“password”);
String url = DBConfig.getDBConfig().getValue(“url”);
System.out.println(driver + ‘\n’ + user + ‘\n’ + pwd + ‘\n’ + url);
}
}
到時調(diào)用的時候
你將DBConfig中放在一個.file文件中 讀出來 下面就是DBConfig文件:是sqlserver的
想連接什么數(shù)據(jù)庫 把driver url改一下就OK了 到網(wǎng)上查
driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:
user=sa
password=
ConnectionFactory.getConnection(); 這樣一句話就連接上了
ConnectionFactory.release(); 就關閉相關對象了
關于jdbc連接數(shù)據(jù)庫封裝的介紹到此就結(jié)束了,不知道你從中找到你需要的信息了嗎 ?如果你還想了解更多這方面的信息,記得收藏關注本站。
數(shù)據(jù)庫運維技術(shù)服務 ? JDBC連接數(shù)據(jù)庫封裝實現(xiàn)方法分享 (jdbc連接數(shù)據(jù)庫封裝)
管理員 普通
分享到:
相關推薦
Java輕松實現(xiàn)數(shù)據(jù)庫格式的刪除操作 (java里刪除數(shù)據(jù)庫格式)
重要性和使用方法 (數(shù)據(jù)庫不能重復的約束條件)
數(shù)據(jù)庫連接關閉判斷方法詳解 (怎么判斷數(shù)據(jù)庫連接connect是否關閉)
05數(shù)據(jù)庫1433:讓你的數(shù)據(jù)管理更高效! (05數(shù)據(jù)庫1433)
如何優(yōu)化數(shù)據(jù)庫的訂單查詢? (數(shù)據(jù)庫題 訂單)
Java數(shù)據(jù)庫操作:如何插入時間戳? (java數(shù)據(jù)庫插入時間戳)
云端儲存數(shù)據(jù)庫數(shù)據(jù)安全保障與便捷性的平衡選擇 (如果將數(shù)據(jù)庫放在云端)
PowerBuilder數(shù)據(jù)庫連接指南,30秒上手! (powerbuilder如何連接數(shù)據(jù)庫)
隨機文章
使用jquery操作數(shù)據(jù)庫,讓前后端互動更方便。 (jquery 與數(shù)據(jù)庫)
如何配置PL/SQL的數(shù)據(jù)庫連接 (plsql配置數(shù)據(jù)庫連接)
如何正確使用數(shù)據(jù)庫表update語句? (數(shù)據(jù)庫表update語句)
MySQL數(shù)據(jù)庫腳本升級:升級數(shù)據(jù)庫與應用程序版本,提高安全性與性能。 (mysql數(shù)據(jù)庫腳本升級)
如何安全、高效地維護郵件地址數(shù)據(jù)庫? (郵件地址數(shù)據(jù)庫)
le擊解決方案 (access數(shù)據(jù)庫 doub)
最近更新
標簽
Linux Linux教程 Linux資訊 MacOS MacOS教程 MacOS資訊 MongoDB MongoDB教程 MongoDB資訊 MSSQL MSSQL錯誤 MySQL mysql教程 MySQL維護 MySQL資訊 Neo4j Neo4j教程 Neo4j資訊 ORACLE Oracle優(yōu)化 oracle內(nèi)部視圖 oracle參數(shù) oracle開發(fā) oracle異常修復 oracle故障處理 oracle教程 oracle維護 oracle視圖 ORACLE資訊 oracle遠程維護 ORA錯誤碼 Redis Redis教程 Redis資訊 SQLServer SQLServer報錯 SQLServer教程 SQLServer資訊 SQL修復 SQL異常 SQL遠程處理 Windows 技術(shù)文檔 操作系統(tǒng) 數(shù)據(jù)庫
- 登錄
- 注冊
安全登錄
立即注冊 忘記密碼?
創(chuàng)新互聯(lián)服務器托管擁有成都T3+級標準機房資源,具備完善的安防設施、三線及BGP網(wǎng)絡接入帶寬達10T,機柜接入千兆交換機,能夠有效保證服務器托管業(yè)務安全、可靠、穩(wěn)定、高效運行;創(chuàng)新互聯(lián)專注于成都服務器托管租用十余年,得到成都等地區(qū)行業(yè)客戶的一致認可。
網(wǎng)頁名稱:JDBC連接數(shù)據(jù)庫封裝實現(xiàn)方法分享(jdbc連接數(shù)據(jù)庫封裝)
當前地址:http://www.dlmjj.cn/article/cdieidi.html


咨詢
建站咨詢
