我正在编写一个用于查看、归档和恢复SQL数据的程序.
调用以下方法数次(5-10),以获取数据库表的所有名称:
public List<string> GetAllTables(string sDatabase)
{
List<string> result = new List<string>();
try
{
using (SqlConnection con = new SqlConnection(dbConnection.conString + sDatabase))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT name FROM sys.Tables", con))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader["name"].ToString());
}
}
}
}
return result;
}
catch (SqlException sqlEx)
{
string methodName = (new System.Diagnostics.StackTrace()).GetFrame(0).GetMethod().Name;
string className = (new System.Diagnostics.StackTrace()).GetFrame(0).GetMethod().DeclaringType.Name;
Debug.Print("Error in class {0} - method: {1}: {2}", className, methodName, sqlEx.Message);
return result;
}
}
错误发生在var reader = command.ExecuteReader()
.奇怪的是,这并不是每次都会发生.每秒恢复都成功,不会引发错误.
异常堆栈跟踪如下所示:
Error in class DatabaseWorker - method: GetAllTables: Transmission-level error when sending the request to the server. (provider: TCP-Provider, error:0 - An existing connection was closed by the remote host.)
by system.Data.SqlClient.SqlConnection.onError(SQLException exception, Boolean breakConnection)
by system.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
by system.Data.SqlClient.TdsParserStateObject.WriteSni()
by system.Data.SqlClient.TdsParserStateObject.ExecuteFlush()
by system.Data.SqlClient.TdsParser.TdsExecuteSQLBatch(String text, Int32 timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj)
by system.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
by system.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
by system.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
by system.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
by system.Data.SqlClient.SqlCommand.ExecuteReader()
for sql_data archiving.fashion model.DatabaseWorker.GetAllTables(String sDatabase)