RESTORE DATABASE 异常终止

RESTORE DATABASE is terminating abnormally

我已经设法编写了一个允许我备份 SQL 服务器数据库的函数,但我正在努力尝试恢复和使用备份版本。

我的代码:

    Try
        Dim confirmBackUp As MsgBoxResult
        confirmBackUp = MsgBox("Are you sure you want to restore?")

        If confirmBackUp = MsgBoxResult.Yes Then  Else Exit Sub
        Dim cmd As New OleDbCommand
        con = New OleDbConnection()

             ' con.Connectionstring is read from an .ini file, but the string is correct

        con.Open()
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "RESTORE DATABASE MaintenanceControl FROM DISK='c:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\Backup\MaintenanceControl.bak'"
        cmd.Connection = con
        cmd.ExecuteNonQuery()

        MsgBox("Database Restored", MsgBoxStyle.OkOnly, "Success")
        con.Close()

    Catch ex As Exception
        errorLog(ex.Message, ex.StackTrace)
        MsgBox("Could not restore database, refer to error log")

    End Try

但是在 .ExecuteNonQuery() 行,我得到以下错误;

RESTORE DATABASE is terminating abnormally.

RESTORE cannot process database 'MaintenanceControl' because it is in use by this session. It is recommended that the master database be used when performing this operation.

这是什么问题?是不是因为con也是连接到实时数据库的名称,不应该给它一个新的字符串?

编辑

我现在已将连接的 Initial Catalog 部分设置为 'Master',并在 con = New OleDbconnection 之前添加了 con.Close() 但是我现在得到的错误是

RESTORE DATABASE is terminating abnormally. Exclusive access could not be obtained because the database is in use.

如果您可以删除并重新创建数据库,则可以使用此语句来删除它:

alter database MaintenanceControl set single_user with rollback immediate; 
drop database SomeDatMaintenanceControl base;

然后根据需要从头开始创建数据库。

删除数据库会破坏数据库,因此在您尝试恢复时不可能有人连接到它。然后你干净地创建数据库。