|  一、常見的連接數據的方式  
    編碼方式,將資料庫配置信息直接寫入JAVA代碼之中Properties屬性文件,將資料庫配置信息寫在屬性文件中,然後在程序中讀取該屬性文件。數據源,用JNDI來獲取DataSource 對像,從而的到Connection對像。Hibernate配置Spring配置     二、屬性文件(.properties)配置與讀取  以MySQL資料庫為例:   1、配置文件users.properties jdbc.drivers=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/databaseName jdbc.username=root jdbc.password=upassword   2、讀取屬性文件   (1)創建Properties的對象;   Properties properties = new Properties(); 這一步也可以這樣做:創建繼承Properties的類,並以單例模式獲取對象。   (2)使用Class對象的getResourceAsStream()方法,把指定的屬性文件讀入到輸入流中,並使用Properties類中的load()方法,從輸入流中讀取屬性列表(鍵/值對);   private String resource = "users.properties"; //假如配置文件名為users.properties InputStream in = getClass().getResourceAsStream(resource); properties.load(in);   (3)在使用資料庫連接時,使用Properties類中的getProperty()方法,通過key獲取value值,從而實現資料庫連接的操作。   String drivers = props.getProperty("jdbc.drivers"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); //返回的是Connection類的實例 Class.forName(drivers); return DriverManager.getConnection(url, username, password);   |