在 vb.net 中备份 SQL 服务器 localdb

Backup SQL Server localdb in vb.net

我想备份我的 SQL 服务器 localdb 数据库。我试过这段代码:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim Sfd As New SaveFileDialog() With {
        .Filter = "Backup file | *.bak",
        .FileName = ""
    }

    If Sfd.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            Cursor = Cursors.WaitCursor

            Dim dbname As String = "RestoDB.mdf"
            Dim sql As String = "Backup database [" + System.Windows.Forms.Application.StartupPath + "\RestoDB.mdf] To DISK = '{Sfd.Filename}'"
            Dim cmd As New SqlCommand(sql, con)
            cmd.ExecuteNonQuery()
            MsgBox("Backup complete")
            Cursor = Cursors.Default
        End If

    End Sub

我收到一条错误消息

does not exist. Make sure that the name is entered correctly.

这是连接字符串:

Private con As New SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\CHAKER\Documents\RestoDB.mdf;Integrated Security=True;Connect Timeout=30")

System.Windows.Forms.Application.StartupPath 不太可能(也不应该是这种情况)是“C:\Users\CHAKER\Documents”。

您可以做的是获取当前用户的文档文件夹并使用它来构建数据库文件的完整路径:

Dim dbName As String = "RestoDB.mdf"
Dim dbFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim dbFullPath = Path.Combine(dbFolder, dbName)
Dim sql = $"Backup database ""{dbFullPath}"" TO DISK = '{Sfd.Filename}'"

(我看到的示例在数据库参数周围使用了双引号,而不是方括号。)

但最好使用连接字符串中的值:

Dim csb = New SqlConnectionStringBuilder("yourConnectionString")
Dim dbFullPath = csb.AttachDBFilename
Dim sql = $"Backup database ""{dbFullPath}"" TO DISK = '{Sfd.Filename}'"

如果连接字符串存储在一个变量中,如果需要编辑它,只需要在一个地方进行更改。

如果您使用的是引入字符串插值之前的 VB 版本,您可以使用

Dim sql = String.Format("Backup database ""{0}"" TO DISK = '{1}'", dbFullPath, Sfd.Filename)

我用这个代码做备份

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim Sfd As New SaveFileDialog() With {
.Filter = "Backup file | *.bak",
.FileName = ""
}
        If Sfd.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            Cursor = Cursors.WaitCursor

            Dim csb = New SqlConnectionStringBuilder("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\CHAKER\Documents\RestoDB.mdf;Integrated Security=True;Connect Timeout=30")
            Dim dbFullPath = csb.AttachDBFilename
            Dim sql = String.Format("Backup database ""{0}"" TO DISK = '{1}'", dbFullPath, Sfd.FileName)
            Dim cmd As New SqlCommand(sql, con)
            cmd.ExecuteNonQuery()
            MsgBox("Backup complete")
            Cursor = Cursors.Default
        End If

    End Sub