掃二維碼與項(xiàng)目經(jīng)理溝通
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
JDBC是Java Database Connectivity的縮寫(xiě),即Java數(shù)據(jù)庫(kù)連接,是Java的一個(gè)標(biāo)準(zhǔn)的接口,定義了一套標(biāo)準(zhǔn)的訪問(wèn)數(shù)據(jù)庫(kù)的接口。JDBC提供了一種基于SQL語(yǔ)句進(jìn)行數(shù)據(jù)庫(kù)操作的方式,使得Java程序能夠訪問(wèn)各種類型的數(shù)據(jù)庫(kù)。

JDBC連接數(shù)據(jù)庫(kù)是Java開(kāi)發(fā)中必不可少的一部分,但是每次使用JDBC連接數(shù)據(jù)庫(kù)時(shí)都需要手動(dòng)編寫(xiě)大量的重復(fù)代碼,這不僅繁瑣而且容易出錯(cuò)。因此,我們通常會(huì)將數(shù)據(jù)庫(kù)的連接和操作封裝起來(lái),以減少代碼的重復(fù)性,提高代碼的重用性和可維護(hù)性。接下來(lái),本文將介紹jdbc連接數(shù)據(jù)庫(kù)封裝實(shí)現(xiàn)方法的詳細(xì)步驟。
實(shí)現(xiàn)步驟
1、定義一個(gè)數(shù)據(jù)庫(kù)連接池類
為了封裝數(shù)據(jù)庫(kù)連接,我們需要定義一個(gè)連接池類,用于維護(hù)數(shù)據(jù)庫(kù)連接。在該類中,我們需要定義一個(gè)數(shù)據(jù)庫(kù)連接池的列表(List)和一個(gè)線程池(ExecutorService),在連接池初始化時(shí),我們需要向連接池添加指定數(shù)量的數(shù)據(jù)庫(kù)連接,同時(shí)創(chuàng)建一個(gè)線程池用于管理數(shù)據(jù)庫(kù)連接的釋放。連接池類的代碼如下:
“`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();
}
}
“`
在該類中,我們使用了單例模式來(lái)保證全局只有一個(gè)ConnectionPool對(duì)象。在getConnection()方法中,我們從連接池中獲取一個(gè)數(shù)據(jù)庫(kù)連接,若該連接已關(guān)閉,則嘗試從池中獲取另一個(gè)連接;在releaseConnection()方法中,我們將數(shù)據(jù)庫(kù)連接釋放回連接池供其他線程使用;在createConnection()方法中,我們使用DriverManager獲取一個(gè)數(shù)據(jù)庫(kù)連接。
2、定義一個(gè)數(shù)據(jù)庫(kù)操作類
除了連接池類之外,我們還需要定義一個(gè)數(shù)據(jù)庫(kù)操作類,用于執(zhí)行各種SQL語(yǔ)句。在該類中,我們需要定義一個(gè)ConnectionPool對(duì)象以獲取數(shù)據(jù)庫(kù)連接,同時(shí)定義一系列的執(zhí)行SQL語(yǔ)句的方法。數(shù)據(jù)庫(kù)操作類的代碼如下:
“`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語(yǔ)句來(lái)自動(dòng)關(guān)閉資源。executeQuery()方法用于執(zhí)行SELECT語(yǔ)句,并返回一個(gè)ResultSet對(duì)象;executeUpdate()方法用于執(zhí)行INSERT、UPDATE、DELETE語(yǔ)句,并返回受影響的行數(shù);executeUpdate()方法還提供了一個(gè)可變參數(shù)的params列表,用于設(shè)置PreparedStatement中的參數(shù)。
3、測(cè)試連接池和數(shù)據(jù)庫(kù)操作類
在完成了連接池和數(shù)據(jù)庫(kù)操作類的定義之后,我們需要對(duì)其進(jìn)行測(cè)試。在測(cè)試之前,我們需要在數(shù)據(jù)庫(kù)中創(chuàng)建一個(gè)名為”test”的數(shù)據(jù)庫(kù),并在該數(shù)據(jù)庫(kù)中創(chuàng)建一個(gè)名為”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`)
);
“`
在測(cè)試類中,我們需要通過(guò)DBHelper對(duì)象來(lái)執(zhí)行各種SQL語(yǔ)句(查詢、插入等),同時(shí)需要手動(dòng)釋放資源。測(cè)試代碼如下:
“`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());
}
}
}
“`
在測(cè)試代碼中,我們首先通過(guò)testConnectionPool()方法測(cè)試連接池的功能,可以看到在連接池已滿的情況下,getConnection()方法會(huì)返回null。然后我們通過(guò)testDBHelper()方法測(cè)試DBHelper類的功能,可以看到在執(zhí)行各種SQL語(yǔ)句時(shí),我們不需要手動(dòng)獲取和釋放數(shù)據(jù)庫(kù)連接,這些操作已經(jīng)被封裝在DBHelper類的方法中了。
相關(guān)問(wèn)題拓展閱讀:
將連接封搭埋裝起來(lái) 一個(gè)工廠類
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(“注冊(cè)驅(qū)動(dòng)失敗”);
e.printStackTrace();
throw new SQLException(“注冊(cè)鍵租驅(qū)動(dòng)失敗”);
}
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();
}
}
}
然后再寫(xiě)一個(gè)配置文稿枝兆件
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);
}
}
到時(shí)調(diào)用的時(shí)候
你將DBConfig中放在一個(gè).file文件中 讀出來(lái) 下面就是DBConfig文件:是sqlserver的
想連接什么數(shù)據(jù)庫(kù) 把driver url改一下就OK了 到網(wǎng)上查
driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:
user=sa
password=
ConnectionFactory.getConnection(); 這樣一句話就連接上了
ConnectionFactory.release(); 就關(guān)閉相關(guān)對(duì)象了
關(guān)于jdbc連接數(shù)據(jù)庫(kù)封裝的介紹到此就結(jié)束了,不知道你從中找到你需要的信息了嗎 ?如果你還想了解更多這方面的信息,記得收藏關(guān)注本站。
數(shù)據(jù)庫(kù)運(yùn)維技術(shù)服務(wù) ? JDBC連接數(shù)據(jù)庫(kù)封裝實(shí)現(xiàn)方法分享 (jdbc連接數(shù)據(jù)庫(kù)封裝)
分享到:
使用jquery操作數(shù)據(jù)庫(kù),讓前后端互動(dòng)更方便。 (jquery 與數(shù)據(jù)庫(kù))
如何配置PL/SQL的數(shù)據(jù)庫(kù)連接 (plsql配置數(shù)據(jù)庫(kù)連接)
如何正確使用數(shù)據(jù)庫(kù)表update語(yǔ)句? (數(shù)據(jù)庫(kù)表update語(yǔ)句)
MySQL數(shù)據(jù)庫(kù)腳本升級(jí):升級(jí)數(shù)據(jù)庫(kù)與應(yīng)用程序版本,提高安全性與性能。 (mysql數(shù)據(jù)庫(kù)腳本升級(jí))
如何安全、高效地維護(hù)郵件地址數(shù)據(jù)庫(kù)? (郵件地址數(shù)據(jù)庫(kù))
le擊解決方案 (access數(shù)據(jù)庫(kù) doub)
Linux Linux教程 Linux資訊 MacOS MacOS教程 MacOS資訊 MongoDB MongoDB教程 MongoDB資訊 MSSQL MSSQL錯(cuò)誤 MySQL mysql教程 MySQL維護(hù) MySQL資訊 Neo4j Neo4j教程 Neo4j資訊 ORACLE Oracle優(yōu)化 oracle內(nèi)部視圖 oracle參數(shù) oracle開(kāi)發(fā) oracle異常修復(fù) oracle故障處理 oracle教程 oracle維護(hù) oracle視圖 ORACLE資訊 oracle遠(yuǎn)程維護(hù) ORA錯(cuò)誤碼 Redis Redis教程 Redis資訊 SQLServer SQLServer報(bào)錯(cuò) SQLServer教程 SQLServer資訊 SQL修復(fù) SQL異常 SQL遠(yuǎn)程處理 Windows 技術(shù)文檔 操作系統(tǒng) 數(shù)據(jù)庫(kù)
安全登錄
立即注冊(cè) 忘記密碼?
創(chuàng)新互聯(lián)服務(wù)器托管擁有成都T3+級(jí)標(biāo)準(zhǔn)機(jī)房資源,具備完善的安防設(shè)施、三線及BGP網(wǎng)絡(luò)接入帶寬達(dá)10T,機(jī)柜接入千兆交換機(jī),能夠有效保證服務(wù)器托管業(yè)務(wù)安全、可靠、穩(wěn)定、高效運(yùn)行;創(chuàng)新互聯(lián)專注于成都服務(wù)器托管租用十余年,得到成都等地區(qū)行業(yè)客戶的一致認(rèn)可。

我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流