properties 配置檔案及自定義 JDBCUtils 工具類
阿新 • • 發佈:2018-12-10
一、properties 配置檔案
相關介紹:
開發中獲得連線的4個引數(驅動、URL、使用者名稱、密碼)通常都存在配置檔案中,方便後期維護,程式如果需要更換資料庫,只需要修改配置檔案即可。
通常情況下,我們習慣使用properties檔案,此檔案我們將做如下要求:
1、檔案位置:任意,建議src下
2、檔名稱:任意,副檔名為properties
3、檔案內容:一行一組資料,格式是“key=value”.
(1)key命名自定義,如果是多個單詞,習慣使用點分隔。例如:jdbc.driver
(2)value值不支援中文,如果需要使用非英文字元,將進行unicode轉換。
二、properties 檔案的建立與編寫
1、properties檔案的建立
src路徑下建立database.properties(其實就是一個文字檔案)
2、properties檔案的編寫(內容如下)
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3296/mybase
username=root
password=123
三、載入配置檔案
採用載入properties檔案獲得流,然後使用Properties物件進行處理。
通過類載入器獲取流物件
1 /* 2 * 載入properties配置檔案 3 * IO讀取檔案,鍵值對儲存到集合 4 * 從集合中以鍵值對方式獲取資料庫的連線資訊,完成資料庫的連線 5 */ 6 public class PropertiesDemo { 7 public static void main(String[] args) throws Exception{ 8 FileInputStream fis = newFileInputStream("database.properties"); 9 System.out.println(fis); 10 //使用類的載入器 11 InputStream in = PropertiesDemo.class.getClassLoader().getResourceAsStream("database.properties"); 12 System.out.println(in); 13 Properties pro = new Properties(); 14 pro.load(in); 15 System.out.println(in); 16 } 17 }
四、通過讀取配置檔案,自定義 JDBC 工具類
1 /* 2 * 編寫資料庫連線的工具類,JDBC工具類 3 * 獲取連線物件採用讀取配置檔案方式 4 * 讀取檔案獲取連線,執行一次,static{} 5 */ 6 public class JDBCUtilsConfig { 7 8 //私有構造器 9 private JDBCUtilConfig(){ 10 } 11 12 private static Connection con ; 13 private static String driverClass; 14 private static String url; 15 private static String username; 16 private static String password; 17 18 static{ 19 try{ 20 readConfig(); 21 Class.forName(driverClass); 22 con = DriverManager.getConnection(url, username, password); 23 }catch(Exception ex){ 24 throw new RuntimeException("資料庫連線失敗"); 25 } 26 } 27 28 //私有方法 29 private static void readConfig()throws Exception{ 30 InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties"); 31 Properties pro = new Properties(); 32 pro.load(in); 33 driverClass=pro.getProperty("driverClass"); 34 url = pro.getProperty("url"); 35 username = pro.getProperty("username"); 36 password = pro.getProperty("password"); 37 } 38 39 //定義靜態方法,返回資料庫的連線物件 40 public static Connection getConnection(){ 41 return con; 42 } 43 44 //釋放資源 45 public static void close(Connection con,Statement stat){ 46 47 if(stat!=null){ 48 try{ 49 stat.close(); 50 }catch(SQLException ex){} 51 } 52 53 if(con!=null){ 54 try{ 55 con.close(); 56 }catch(SQLException ex){} 57 } 58 59 } 60 61 //釋放資源 62 public static void close(Connection con,Statement stat , ResultSet rs){ 63 if(rs!=null){ 64 try{ 65 rs.close(); 66 }catch(SQLException ex){} 67 } 68 69 if(stat!=null){ 70 try{ 71 stat.close(); 72 }catch(SQLException ex){} 73 } 74 75 if(con!=null){ 76 try{ 77 con.close(); 78 }catch(SQLException ex){} 79 } 80 81 } 82 }