將資料庫連線參數外部化至 Database.Properties,程式碼無需重編譯即可切換環境,提升部署彈性。
jdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver
jdbc.url=jdbc:odbc:mydata
jdbc.username=system
jdbc.password=manager
封裝連線取得、查詢、更新、插入、刪除與關閉等常用操作,採用 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 */ }
}
PreparedStatement 防止 SQL 注入。AutoCloseable 配合 try-with-resources 自動釋放資源。