这是我恢复SQL Server数据库的vb.net代码,我认为代码不包含错误,所以在执行代码时它似乎没有错,但它不会恢复数据库。
请帮我找出错误。我在网上搜索了很多,但没有找到解决问题的方法。
Sub restore_db()
Dim con As New SqlConnection("Data Source=HP;Database=Master;integrated security=SSPI;")
con.Open()
Dim filename As String
Dim strQuery As String
Dim objdlg As New OpenFileDialog
objdlg.FileName = "service_station"
objdlg.Filter = "SQL Server database backup files|*.bak"
objdlg.ShowDialog()
filename = objdlg.FileName
strQuery = "ALTER DATABASE service_station set SINGLE_USER WITH ROLLBACK IMMEDIATE"
strQuery = "RESTORE DATABASE service_station FROM disk='" & filename & "' WITH REPLACE,RECOVERY"
strQuery = "ALTER DATABASE service_station SET MULTI_USER WITH ROLLBACK IMMEDIATE"
Dim cmd As SqlCommand
cmd = New SqlCommand(strQuery, con)
cmd.ExecuteNonQuery()
con.Close()
End Sub
答案 0 :(得分:2)
您不断覆盖查询值:
strQuery = "ALTER DATABASE ..."
strQuery = "RESTORE DATABASE ..."
strQuery = "ALTER DATABASE ..."
将导致strQuery
值仅包含最后一个字符串。相反,你需要做这样的事情:
' First query
strQuery = "ALTER DATABASE ..."
Dim cmd As SqlCommand = New SqlCommand(strQuery, con)
cmd.ExecuteNonQuery()
' Second query
strQuery = "RESTORE DATABASE ..."
cmd = New SqlCommand(strQuery, con)
cmd.ExecuteNonQuery()
' Third query
strQuery = "ALTER DATABASE ..."
cmd = New SqlCommand(strQuery, con)
cmd.ExecuteNonQuery()