简体   繁体   中英

Restore SQL Server localdb in vb.net

I want to restore a SQL Server localdb database. I tried with this code:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim ofd As New OpenFileDialog() With
        {
            .Filter = "Backup file | *.bak",
            .FileName = ""
        }

    If ofd.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("RESTORE DATABASE ""{0}"" From DISK = '{1}'", dbFullPath, ofd.FileName)
            Dim cmd As New SqlCommand(sql, con)
            cmd.ExecuteNonQuery()
            MsgBox("Restore complete")
            Cursor = Cursors.Default

        End If

    End Sub

I get this exception:

RESTORE cannot process database 'C:\Users\CHAKER\Documents\RestoDB.mdf' because it is in use by this session. It is recommended that the master database be used when performing this operation.

You have a number of issues with your code:

  • Your primary issue: you are restoring a database by filename, but you have already attached it using AttachDbFileName , and such a database cannot be restored over. Using AttachDbFileName is in any case deprecated. You should instead attach it to LocalDB using the normal CREATE DATABASE FOR ATTACH syntax.
  • Preferably you should not hard-code your connection string, store it in a settings file instead.
  • You need to dispose your connection and command objects with Using . Do not cache the connection object.
  • Do not block the thread with a MessageBox while the connection is open
  • You should use parameterization on the RESTORE command, rather than injecting the names directly
In settings file:
ConnectionString "Data Source=(LocalDB)\v11.0;Initial Catalog=RestoDB;Integrated Security=True;Connect Timeout=30"
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim ofd As New OpenFileDialog() With
        {
            .Filter = "Backup file | *.bak",
            .FileName = ""
        }

    If ofd.ShowDialog <> System.Windows.Forms.DialogResult.OK Then Exit Sub

    Try
        Cursor = Cursors.WaitCursor
        Const sql = "RESTORE DATABASE @DB From DISK = @FileName"
        Using con As New SqlConnection(Properties.ConnectionString),
              cmd As New SqlCommand(sql, con)
            cmd.Parameters.Add("@DB", SqlDbType.NVarChar, 128).Value = con.Database
            cmd.Parameters.Add("@FileName", SqlDbType.NVarChar, 255).Value = ofd.FileName
            cmd.ExecuteNonQuery()
        End Using
        MsgBox("Restore complete")
    End Try
    Catch ex As Exception
        MsgBox("Error: " + ex.Message)
    End Catch
    Finally
        Cursor = Cursors.Default
    End Finally

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM