JAVA讀取屬性檔案來串連資料庫

來源:互聯網
上載者:User

把資料庫設定檔的資訊寫在檔案中,並且儲存在項目內,在程式中讀取檔案中的資訊,從而進行資料庫連接。在JAVA中提供

Properties類,來讀取.properties(屬性)檔案。

以下是:db.properties檔案 driver=com.microsoft.sqlserver.jdbc.SQLServerDriver url=jdbc:sqlserver://localhost:1433;DatabaseName=books user=sa password=123

下面的Env.java檔案實現了db.properties檔案的載入工作,代碼如下:

import java.io.IOException; import java.io.InputStream; import java.util.Properties; /**  * 此類屬於一個單例模式的例子  * 用來建立擷取對象執行個體  * @author 周尚武  * 時間:2008年12月8日23:14:24  */ public class Env {       private static Properties prop = new Properties();     private static Env instance = new Env();          //初始化屬性prop對象     private Env(){         InputStream in = this.getClass().getResourceAsStream("/db.properties");         try {             prop.load(in);         } catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }     }     /*      * 返回env的單例對象      */     public static Env getInstance() {         return instance;     }     /*      * 讀屬性對象prop讀對應的健值      */     public String getProperty(String key){         return (String) prop.get(key);     }    }

下面一個類為測試類別: import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropTest {     public static void main(String[] args) {                 Env env =  Env.getInstance();         String username = env.getProperty("user");         System.out.println(username);     } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.