首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

透過 JDBC Driver 獲取資料庫連線完整教學

     編輯:Java 綜合教學

透過 JDBC Driver 獲取資料庫連線完整教學

在 Java 開發中,建立資料庫連線是基礎且關鍵的步驟。本文將詳細介紹如何透過 JDBC Driver 介面獲取資料庫連線,並展示從硬編碼到使用屬性配置檔案解耦的進階做法。

專案結構準備

首先看一下專案結構:在當前套件下有一個 jdbc.properties 配置檔案,專案根目錄下的 lib 資料夾存放 MySQL 驅動 JAR 包(mysql-connector-java-5.1.39-bin.jar)。

專案結構圖

方法一:直接使用 Driver 實現類獲取連線(硬編碼方式)

Driver 是一個介面,資料庫廠商必須提供實現。我們可以透過 Driver 實現類的物件來獲取資料庫連線。

@Test
public void testDriver() throws Exception {
    // 1. 建立 Driver 實現類的物件
    Driver driver = new com.mysql.jdbc.Driver();
    
    // 2. 準備連線資訊:url、user、password
    String url = "jdbc:mysql://localhost:3306/test";
    Properties info = new Properties();
    info.put("user", "root");
    info.put("password", "123456");
    
    // 3. 呼叫 Driver.connect() 獲取連線
    Connection connection = driver.connect(url, info);
    System.out.println(connection); // com.mysql.jdbc.JDBC4Connection@73f712
}

方法二:使用屬性檔案解耦(推薦做法)

為了讓程式更通用、不修改原始碼就能切換資料庫,我們將驅動類全名、URL、帳號、密碼放入配置檔案,透過反射動態載入。

配置檔案內容 (jdbc.properties)

# Oracle 範例
#driver=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#password=java

# MySQL 實際配置
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test
user=root
password=123456

通用獲取連線方法

public Connection getConnection() throws Exception {
    String driverClass = null;
    String jdbcUrl = null;
    String user = null;
    String password = null;
    
    // 讀取類路徑下的 jdbc.properties
    InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
    Properties properties = new Properties();
    properties.load(in);
    
    driverClass = properties.getProperty("driver");
    jdbcUrl = properties.getProperty("jdbcUrl");
    user = properties.getProperty("user");
    password = properties.getProperty("password");
    
    // 透過反射建立 Driver 物件
    Driver driver = (Driver) Class.forName(driverClass).newInstance();
    
    Properties info = new Properties();
    info.put("user", user);
    info.put("password", password);
    
    // 獲取資料庫連線
    Connection connection = driver.connect(jdbcUrl, info);
    return connection;
}

@Test
public void testGetConnection() throws Exception {
    System.out.println(getConnection()); // com.mysql.jdbc.JDBC4Connection@1556938
}

這樣當需要連線其他資料庫時,只需修改屬性檔案即可,完全不需要動到 Java 程式碼,實現了真正的解耦。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved