2013-04-25 92 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