我正在尝试使用针对 sql server Express 的命令验证我刚刚在 c# 中完成的备份
string _commandText = string.Format("RESTORE VERIFYONLY FROM DISK = '{0}'", backupLocation);
SqlDataReader _sqlDataReader = SqlHelper.ExecuteReader("BookssortedSQLDbConnection", CommandType.Text, _commandText);
如果我在 SSMS 中执行命令,它会返回“文件 1 上的备份集有效。”但是我怎样才能将这条消息返回到我的代码中呢?
读取器将无法工作,因为没有行被返回。
注意:我已尝试使用 SMO.Restore 对象来尝试验证它,但它不起作用,这就是我这样做的原因。
_restore.SqlVerify(srv, out _errorMessage); //returns false even though bakcup is fine
顺便说一句 - 愿意接受建议,因为我认为这不是实现我想要做的事情的理想方式
最佳答案
信息性消息(严重性低于 10)和 PRINT 输出返回给客户端,并由 SqlConnection
实例作为 InfoMessage
事件引发。每个事件都包含一组 SqlError
对象(这与 SqlException.Errors
中使用的类相同)。
这是一个显示连接状态更改、信息消息和异常的完整示例。请注意,我使用 ExecuteReader
而不是 ExecuteNonQuery
,但信息和异常结果是相同的。
namespace Test
{
using System;
using System.Data;
using System.Data.SqlClient;
public class Program
{
public static int Main(string[] args)
{
if (args.Length != 2)
{
Usage();
return 1;
}
var conn = args[0];
var sqlText = args[1];
ShowSqlErrorsAndInfo(conn, sqlText);
return 0;
}
private static void Usage()
{
Console.WriteLine("Usage: sqlServerConnectionString sqlCommand");
Console.WriteLine("");
Console.WriteLine(" example: \"Data Source=.;Integrated Security=true\" \"DBCC CHECKDB\"");
}
public static void ShowSqlErrorsAndInfo(string connectionString, string query)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.StateChange += OnStateChange;
connection.InfoMessage += OnInfoMessage;
SqlCommand command = new SqlCommand(query, connection);
try
{
command.Connection.Open();
Console.WriteLine("Command execution starting.");
SqlDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
Console.WriteLine("Rows returned.");
while (dr.Read())
{
for (int idx = 0; idx < dr.FieldCount; idx++)
{
Console.Write("{0} ", dr[idx].ToString());
}
Console.WriteLine();
}
}
Console.WriteLine("Command execution complete.");
}
catch (SqlException ex)
{
DisplaySqlErrors(ex);
}
finally
{
command.Connection.Close();
}
}
}
private static void DisplaySqlErrors(SqlException exception)
{
foreach (SqlError err in exception.Errors)
{
Console.WriteLine("ERROR: {0}", err.Message);
}
}
private static void OnInfoMessage(object sender, SqlInfoMessageEventArgs e)
{
foreach (SqlError info in e.Errors)
{
Console.WriteLine("INFO: {0}", info.Message);
}
}
private static void OnStateChange(object sender, StateChangeEventArgs e)
{
Console.WriteLine("Connection state changed: {0} => {1}", e.OriginalState, e.CurrentState);
}
}
}
关于c# - 如何获取Sql Server系统消息的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809529/