2011-06-22 49 views
0

請看下面的代碼爲MSSQL Server 2005的加載性質在文件中使用

屬性文件

driver=com.microsoft.sqlserver.jdbc.SQLServerDriver 
url=jdbc:sqlserver://127.0.0.1:1433;databaseName=LibMgmtSys 
user=sa 
password=passwrod 

連接文件

public class DBConnection { 

    static Properties dbproperties; 

    public static Connection getConnection() throws Exception { 
     Connection conn = null; 
     InputStream dbInputStream = null; 
     dbInputStream = DBConnection.class.getResourceAsStream("jdbc.properties"); 

     try { 
      dbproperties.load(dbInputStream); 
      Class.forName(dbproperties.getProperty("driver")); 
      conn = DriverManager.getConnection(dbproperties.getProperty("url"), 
        dbproperties.getProperty("user"), 
        dbproperties.getProperty("password")); 
     } catch (Exception exp) { 
      System.out.println("error : " + exp); 
     } 

     return conn; 
    } 
} 

上面的代碼給我當我嘗試執行dbproperties.load(dbInputStream)時出現NullPointException。難道我做錯了什麼???

回答

2

您沒有實例化dbproperties,因此當您嘗試對其進行解引用時它爲空(dbproperties.load(dbInputStream);)。將其更改爲:

try { 
     dbproperties = new Properties(); 
     dbproperties.load(dbInputStream); 
+0

LOL。那很簡單。謝謝。 – Rabin