.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.");
}
}
ConfigurationException似乎被depricated。想想如果沒有其他人有更好的建議,我會用DataException去。謝謝! – David 2013-04-25 07:57:45
是的,ConfigurationErrorsException是MS建議使用的。 – 2013-04-25 08:14:56