RESTORE无法处理数据库'MyDataBaseName',因为此会话正在使用它

时间:2016-12-23 10:52:26

标签: sql sql-server-2014

我正在尝试在我的vb.net windows应用程序中恢复数据库备份(.BAK)文件。但我收到此错误(RESTORE无法处理数据库'MyDataBaseName',因为它正在被此会话使用。建议在执行此操作时使用master数据库.RESTORE DATABASE异常终止。)这里是代码恢复过程:

Private Sub DbRestoreButton_Click(sender As Object, e As EventArgs) Handles DbRestoreButton.Click
    If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
        Dim SourcePath As String = OpenFileDialog1.FileName
        Dim DatabaseName As String = "MyDatabaseName"

        RestoreDatabase(DatabaseName, SourcePath)
    End If
End Sub
Private Sub RestoreDatabase(ByVal DatabaseName As String, ByVal SourcePath As String)

    Try
        Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
        Using conn As New SqlConnection(connString)

            Using cmd As New SqlCommand("RESTORE DATABASE @DatabaseName FROM DISK = @SourcePath WITH REPLACE", conn)
                conn.Open()
                cmd.Parameters.AddWithValue("@DatabaseName", DatabaseName)
                cmd.Parameters.AddWithValue("@SourcePath", SourcePath)

                cmd.ExecuteNonQuery()
                MessageBox.Show("Database Restored Succesfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)

            End Using
        End Using

    Catch ex As ApplicationException
        MsgBox("ERROR" & ex.Message, "ERROR")
    End Try

End Sub

有谁能告诉我如何解决这个问题?

感谢。

0 个答案:

没有答案