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

基於屬性檔的 Java 資料庫連線工具類實作

     編輯:Java 相關知識

設計理念

將資料庫連線參數外部化至 Database.Properties,程式碼無需重編譯即可切換環境,提升部署彈性。

屬性檔範例

jdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver
jdbc.url=jdbc:odbc:mydata
jdbc.username=system
jdbc.password=manager

核心類別:DBManager

封裝連線取得、查詢、更新、插入、刪除與關閉等常用操作,採用 Class.getResourceAsStream 讀取類路徑下的屬性檔,避免硬編碼路徑。

public class DBManager {
    private Connection conn = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    private String sqlwords = null;

    public Connection getConnection() throws SQLException, IOException, Exception {
        Properties props = new Properties();
        InputStream in = getClass().getResourceAsStream("/Database.Properties");
        props.load(in);

        String drivers = props.getProperty("jdbc.drivers");
        if (drivers != null) System.setProperty("jdbc.drivers", drivers);

        String url = props.getProperty("jdbc.url");
        String username = props.getProperty("jdbc.username");
        String password = props.getProperty("jdbc.password");

        Class.forName(drivers);
        return DriverManager.getConnection(url, username, password);
    }

    public DBManager() {
        try {
            conn = getConnection();
            stmt = conn.createStatement();
            System.out.println("Connect Database is Ok!");
        } catch (Exception e) {
            System.out.println("Connect Database Failed!: " + e);
        }
    }

    public ResultSet executeQuery(String sqlwords) { /* ... */ }
    public boolean executeUpdate(String sqlwords) { /* ... */ }
    public boolean executeInsert(String sqlwords) { /* ... */ }
    public boolean executeDelete(String sqlwords) { /* ... */ }
    public boolean close() { /* 依序關閉 rs、stmt、conn */ }
}

使用建議

  • 生產環境建議改用連線池(如 DBCP、HikariCP)替代直連。
  • 加入 PreparedStatement 防止 SQL 注入。
  • 實作 AutoCloseable 配合 try-with-resources 自動釋放資源。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved