.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.");
}
}