kur*_*asa 4 c# sql sql-server smo
我正在尝试使用针对sql server Express的命令验证我刚刚在c#中完成的备份
string _commandText = string.Format("RESTORE VERIFYONLY FROM DISK = '{0}'", backupLocation);
SqlDataReader _sqlDataReader = SqlHelper.ExecuteReader("BookssortedSQLDbConnection", CommandType.Text, _commandText);
Run Code Online (Sandbox Code Playgroud)
如果我在SSMS中执行该命令,则返回"文件1上的备份集有效".但是如何才能将此消息重新发送到我的代码中?
读者无法工作,因为没有返回任何行.
注意:我已经尝试过SMO.Restore对象来尝试验证它,但它不起作用,这就是我这样做的原因.
_restore.SqlVerify(srv, out _errorMessage); //returns false even though bakcup is fine
Run Code Online (Sandbox Code Playgroud)
BTW - 接受建议,因为我不认为这是实现我想要做的事情的理想方式
dev*_*uff 14
信息性消息(严重性小于10)和PRINT输出将返回给客户端,InfoMessage并由SqlConnection实例引发为事件.每个事件都包含一组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);
}
}
}
Run Code Online (Sandbox Code Playgroud)