2013-04-25 96 views
0

.NET中是否存在「內置」異常DatabaseNotFound我可以將其用於連接數據庫服務器以執行維護任務的程序嗎?拋出未找到數據庫異常

我覺得應該有,但我一直沒能找到它。在下面的代碼中,您會看到我檢查(在app.config中定義的)數據庫的存在。

XML文件:

<DatabaseConnection source="myLaptop" username="user" password="pass" defaultDatabase="DB1"> 
    <database companyIdentTable="tableA" companyIdentField="fieldA">Database_A</database> 
    <database companyIdentTable="tableB" companyIdentField="fieldB">Database_B</database> 
</DatabaseConnection> 

C#代碼:

for (int i = 0; i < appSettings.DatabaseConnection.database.Length; i++) 
{ 
    string database = builder.QuoteIdentifier(appSettings.DatabaseConnection.database[i].Value); //Security measure 
    command = new SqlCommand("SELECT COUNT(1) FROM master.dbo.sysdatabases WHERE name='" + database + "'", conn); 
    if ((int)command.ExecuteScalar() <= 0) 
    { 
     Log("Database '" + appSettings.DatabaseConnection.database[i].Value + "' was not found. Service shutting down.", true); 
     //TODO - throw a more specific exception! 
     throw new Exception("Database '" + appSettings.DatabaseConnection.database[i].Value + "' was not found. Service shutting down."); 
    } 
} 

回答

2

最接近的匹配將是

  • System.Configuration.ConfigurationErrorsException
  • System.Data.DataException

由於更容易配置錯誤(指定無效的DB名稱),你的情況比DB錯誤(如果未成功創建的數據庫)的第一選擇會更好。

如果你想要一個特定的異常,你應該從其中一個派生出來並創建你自己的自定義異常類。

+0

ConfigurationException似乎被depricated。想想如果沒有其他人有更好的建議,我會用DataException去。謝謝! – David 2013-04-25 07:57:45

+0

是的,ConfigurationErrorsException是MS建議使用的。 – 2013-04-25 08:14:56