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

JDBC 數據庫連接工具類三種模式:硬編碼、參數傳遞與 Properties 外部化配置

     編輯:Java 相關知識

統一工具類設計

package com.cai.jdbc;

import java.sql.*;
import java.util.Properties;

public class ConnectionUtil {

    // 模式 1:方法內硬編碼(僅供測試/演示)
    public Connection getConnection() {
        return getConnection(
            "com.mysql.jdbc.Driver",
            "jdbc:mysql://localhost:3306/stud",
            "root", "root"
        );
    }

    // 模式 2:參數傳遞(靈活但調用處耦合配置)
    public Connection getConnection(String driver, String url, String user, String pwd) {
        try {
            Class.forName(driver);
            return DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            throw new RuntimeException("獲取連接失敗", e);
        }
    }

    // 模式 3:Properties 文件外部化(生產推薦)
    public Connection openConnection() {
        Properties props = new Properties();
        try (InputStream in = getClass().getClassLoader()
                .getResourceAsStream("DBConfig.properties")) {
            props.load(in);
            String driver = props.getProperty("driver");
            String url = props.getProperty("url");
            String user = props.getProperty("user");
            String pwd = props.getProperty("password");
            Class.forName(driver);
            return DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            throw new RuntimeException("加載配置失敗", e);
        }
    }
}

DBConfig.properties 示例

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/stud
user=root
password=root

三種模式對比

模式優點缺點適用場景
硬編碼簡單直接重新編譯才能改配置,密碼明文入庫單元測試、快速原型
參數傳遞運行期動態決定調用鏈層層透傳,配置分散多數據源動態切換
Properties 文件配置與代碼分離,易維護、易加密需約定文件路徑/命名生產環境標準做法

生產級增強建議

  • 引入連接池:HikariCP / Druid / DBCP2,替換 DriverManager
  • 配置加密:密碼字段 AES 加密,讀取時解密
  • 多環境隔離:DBConfig-dev.properties / DBConfig-prod.properties,啟動參數指定
  • 資源關閉:使用 try-with-resources 自動歸還連接

測試主程序

public static void main(String[] args) {
    ConnectionUtil cu = new ConnectionUtil();
    System.out.println("1. 硬編碼: " + cu.getConnection());
    System.out.println("2. 參數傳遞: " + cu.getConnection("driver","url","user","pwd"));
    System.out.println("3. Properties: " + cu.openConnection());
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved