[英]SQL Server database backup progress using C#
My requirement is to:我的要求是:
I have this code:我有这个代码:
protected void Backup_click(object sender, EventArgs e)
{
var sqlQuery = "EXEC [Test].[dbo].[Usp_Test_Backup_Database] @BackupLabel = 'DB_TEST_1_18_PostScript'";
using (var connection = new SqlConnection(ConnectionString))
{
await connection.OpenAsync();
using (var tran = connection.BeginTransaction())
{
using (var command = new SqlCommand(sqlQuery, connection, tran))
{
try
{
await command.ExecuteNonQueryAsync();
}
catch (Exception)
{
tran.Rollback();
throw;
}
tran.Commit();
}
}
}
}
This takes the backup.这需要备份。 Usually I SSMS to my server, and execute back up progress script which has field - PERCENTAGE (10, 20, 34, 70. etc)
通常我 SSMS 到我的服务器,并执行备份进度脚本,其中包含字段 - PERCENTAGE (10, 20, 34, 70. etc)
Running with multiple thoughts:带着多重想法奔跑:
Create a new button on my UI and execute progress scripts, read the percentage values and update the value in some label?在我的 UI 上创建一个新按钮并执行进度脚本,读取百分比值并更新某个标签中的值?
Or include one more CMD statement to execute backup scripts along with the backup code?或者再包含一个 CMD 语句来执行备份脚本和备份代码?
Any suggestions?有什么建议?
You can send messages from SQL Server to your Applicatio using PRINT
or RAISERROR
.您可以使用
PRINT
或RAISERROR
将消息从 SQL Server 发送到您的应用程序。 If you need to ensure the message is going to be send you should use RAISEERROR and NOWAIT:如果您需要确保消息将被发送,您应该使用 RAISEERROR 和 NOWAIT:
RAISERROR (N'working', 10,1) WITH NOWAIT
The Format is as follows as stated in the docs :格式如下文档中所述:
RAISERROR (N'This is message %s %d.', -- Message text.
10, -- Severity,
1, -- State,
N'number', -- First argument.
5); -- Second argument.
-- The message text returned is: This is message number 5.
You can then subscribe to the message events by using the InfoMessage
event of your SqlConnection
.然后,您可以使用
SqlConnection
的InfoMessage
事件订阅消息事件。
var sqlQuery = @"RAISERROR (N'working', 10,1) WITH NOWAIT";
using (var connection = new SqlConnection(@"Server=localhost\SQLExpress;Database=master;Trusted_Connection=True;"))
{
await connection.OpenAsync();
connection.InfoMessage += (sender, args) =>
{
foreach (var element in args.Errors.OfType<SqlError>())
{
Console.WriteLine($"Class: {element.Class} LineNumber: {element.LineNumber} Message: {element.Message} Number: {element.Number} Procedure: {element.Procedure}");
}
};
using (var command = new SqlCommand(sqlQuery, connection))
{
await command.ExecuteNonQueryAsync();
}
}
Note that SQL Server sends information messages it self and that you can also define your own messages .请注意,SQL Server 会自行发送信息消息,您也可以定义自己的消息。 When a message it of type error the client connection is going to be closed sooner or later so you need to be a little careful what type of message you choose for your own messages.
当消息类型为错误时,客户端连接迟早会关闭,因此您需要小心为自己的消息选择什么类型的消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.