以 連接資料庫 中的程式為例,如下:
package onlyfun.caterpillar; import java.sql.*; public class DBConnectionDemo { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/GUESTBOOK"; String user = "caterpillar"; String password = "123456"; try { Class.forName(driver); Connection conn = DriverManager.getConnection(url, user, password); if(conn != null && !conn.isClosed()) { System.out.println("資料庫連線測試成功!"); conn.close(); } } catch(ClassNotFoundException e) { System.out.println("找不到驅動程式類別"); e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } } }
其中的driver、url、user與password等設定,我們並不用撰寫在程式之中,而可以將之撰寫在一個.properties檔案中,例如:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/GUESTBOOK user=caterpillar password=123456
=左邊設定的是key,右邊是value,我們可以使用java.util.Properties來讀取這個屬性設定檔,根據key來取得value,例如:
package onlyfun.caterpillar;
import java.util.Properties; import java.sql.*; public class DBConnectionDemo { private static Properties props;
private static void loadProperties() { props = new Properties(); try { props.load(new FileInputStream("config.properties")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private static String getConfig(String key) { return props.getProperty(key); } public static void main(String[] args) { loadProperties();
String driver = getConfig("driver"); String url = getConfig("url"); String user = getConfig("user"); String password = getConfig("password");
try { Class.forName(driver); Connection conn = DriverManager.getConnection(url, user, password); if(conn != null && !conn.isClosed()) { System.out.println("資料庫連線測試成功!"); conn.close(); } } catch(ClassNotFoundException e) { System.out.println("找不到驅動程式類別"); e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } } }
如此一來,將來若想改變屬性設定,則直接修改.properties檔案的內容即可,而不用修改原始碼再重新編譯。
|