我正在处理 SQL Server 的“准备好连接”状态和我的数据库启动时间之间的相当长的延迟。有时需要超过 2 分钟。这就是为什么我有时会在数据库联机之前尝试连接到数据库的原因。你知道吗,如何减少“准备连接”和启动数据库之间的时间?或者我如何确定数据库在线以从我的 C# 应用程序连接到它?
基本上我有一些连接字符串的连接“缓存”。这当然发生在第一次连接时,所以我的连接代码非常简单:
var result = new SqlConnection();
result.ConnectionString = "some connection string here";
try
{
result.Open()
}
catch (Exception ex)
{
//some logging stuff here
throw;
}
这是 C# 异常:
System.Data.SqlClient.SqlException: Cannot open database "XXX" requested by the login. The login failed.
这是 SQL Server 日志:
2014-03-31 08:21:05.65 - SQL Server is now ready for client connections. This is an informational message; no user action is required.
2014-03-31 08:21:09.21 - Recovery completed for database model (database ID 3) in 1 second(s) (analysis 234 ms, redo 0 ms, undo 514 ms.) This is an informational message only. No user action is required.
2014-03-31 08:21:11.52 - Error: 18456, Severity: 14, State: 38.
2014-03-31 08:21:11.52 - Login failed for user 'YYY'. Reason: Failed to open the explicitly specified database. [CLIENT: ]
2014-03-31 08:21:13.88 - Clearing tempdb database.
2014-03-31 08:21:21.38 - Recovery completed for database msdb (database ID 4) in 2 second(s) (analysis 327 ms, redo 0 ms, undo 468 ms.) This is an informational message only. No user action is required.
2014-03-31 08:21:32.98 - Starting up database 'tempdb'.
2014-03-31 08:21:40.30 - The Service Broker protocol transport is disabled or not configured.
2014-03-31 08:21:40.41 - The Database Mirroring protocol transport is disabled or not configured.
2014-03-31 08:21:41.50 - Recovery is complete. This is an informational message only. No user action is required.
2014-03-31 08:21:41.52 - Service Broker manager has started.
2014-03-31 08:23:41.87 - Starting up database 'XXX'.
最佳答案
基于 this link ,最佳做法是查询 Collation 属性的值。
A database that has just come online is not necessarily ready to accept connections. To identify when a database can accept connections, query the collation_name column of sys.databases or the Collation property of DATABASEPROPERTYEX.
因此当 Collation 属性不为 null 时,数据库已准备好进行连接。查询看起来像这样
SELECT DATABASEPROPERTYEX('MyDatabase', 'Collation')
关于c# - 当数据库未启动但 SQL Server 已准备好连接时出现 SqlException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25442908/