我已经设法编写了一个函数,允许我备份SQL Server数据库,但我正在努力尝试恢复和使用备份版本。
我代码: 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 FilesMicrosoft SQL ServerMSSQL10_50.SQLEXPRESSMSSQLBackupMaintenanceControl.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异常终止。
RESTORE无法处理数据库'MaintenanceControl',因为该会话正在使用该数据库。建议使用主数据库执行该操作。
有什么问题吗?是因为con也是连接到实时数据库的名称,不应该给它一个新的字符串吗?
编辑
我现在已经将连接的Initial Catalog
部分设置为'Master',以及在con = New OleDbconnection
之前添加con.Close(),但是我现在得到的错误是
RESTORE DATABASE异常终止。无法获得独占访问权限,因为数据库正在使用中。
如果您不介意删除并重新创建数据库,您可以使用以下语句,它将允许您删除数据库:
alter database MaintenanceControl set single_user with rollback immediate;
drop database SomeDatMaintenanceControl base;
,然后根据需要从头创建数据库。
删除数据库将破坏数据库,因此当您尝试恢复时,不可能有人连接到它。然后您可以干净地创建数据库。