以 连接数据库 中的程序为例,如下:
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档案中,例如:
xdriver=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档案的内容即可,而不用修改原始码再重新编译。