在我的应用程序中,我希望show有SQL Query进度。例如,假设用户单击了一个备份按钮,那么我希望他能够查看他所进行的查询的进度,以防数据库太大而无法恢复或备份。首先,我尝试通过假设在开始备份之前数据库可能占用多少磁盘空间,然后使用复制速率来估计备份可能需要的时间。但不幸的是我失败了。然后幸运的是,我找到了一个可爱的T-SQL命令,用于显示SSMS中使用的统计数据,它只是使用额外的行' With Stats = [Some integer] e.g. 1, 10, 20, etc
'但这是问题所在。我无法找到任何与Vb.Net即我的应用程序一起工作的工作。
我从this link(www.mssqltips.com)找到了这个很棒的查询。如果您打开网站,可以看到几个显示此内容的示例。
获取统计信息的代码:
Use dbName Backup dbName To Disk='BackupLocation' With STATS = 10
编辑#1:
现在添加这些内容的代码确实显示了我正在搜索的InfoMessage,但仍然没用,因为只有在完整操作完成时才显示。 但我想要的是动态显示它们。
有效的代码:
AddHandler con.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
Private Sub OnInfoMessage(ByVal sender As Object, ByVal e As System.Data.SqlClient.SqlInfoMessageEventArgs)
strInfo.AppendLine(e.Message)
txtMsg.Text = strInfo.ToString
End Sub
我的完整代码:
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Text
Public Class BackupForm
Dim ConnectionString As String = My.Settings.LADBConnectionString
Dim con As SqlConnection = New SqlConnection(ConnectionString)
Dim cmd As New SqlCommand()
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Using OFD As New SaveFileDialog
With OFD
.FileName = "Backup " + Now.ToString("dd-MM-yyyy")
.Filter = "Log Application Backup |*.bak"
.CheckFileExists = False
.OverwritePrompt = False
Select Case .ShowDialog
Case DialogResult.OK
If .FileName <> "" Then
txtBackup.Text = .FileName
End If
End Select
End With
End Using
End Sub
Private Sub btnBackup_Click(sender As Object, e As EventArgs) Handles btnBackup.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Dim strInfo As New StringBuilder
Private Sub OnInfoMessage(ByVal sender As Object, ByVal e As System.Data.SqlClient.SqlInfoMessageEventArgs)
strInfo.AppendLine(e.Message)
txtMsg.Text = strInfo.ToString
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim backupQuery As String = $"use LDDB Backup database LDDB to Disk='{txtBackup.Text}' With STATS = 1"
Try
con.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = backupQuery
cmd.Connection = con
AddHandler con.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
con.Close()
con.Dispose()
End Try
End Sub
Private Sub BackupForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class