Error Message: Exclusive access could not be obtained because the
database is in use. restore database is terminating abnormally.
My Backup code works but I don't know why this restore code doesn't work.
Try
Dim con2 As SqlConnection
Dim com2 As SqlCommand
Dim filename2 As String
Dim strquery2 As String
Dim database2 As String
Dim get_servername2 As String
'get the value selected in Database Name Dropdown Menu
database2 = Database_NameComboBox.Text
'get the value selected in Server Name Dropdown Menu
get_servername2 = Server_NameComboBox.Text.Trim
Dim opendlg As New OpenFileDialog
Dim constr2 As String
' set SQL connection data source using default Master Database
constr2 = "Data Source=" & get_servername2 & ";Initial Catalog=master;Integrated Security=SSPI"
' open SQL Database to restore
If opendlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.Cursor = Cursors.WaitCursor
con2 = New SqlConnection(constr2)
con2.Open()
filename2 = opendlg.FileName
strquery2 = "Restore database " & database2 & " from disk='" & filename2 & "'"
' execute command
Try
com2 = New SqlCommand(strquery2, con2)
com2.ExecuteNonQuery()
MessageBox.Show("Database " & database2 & " has been Restored Successfully", "IBP Legal Aid Case Management System - Restore Database", MessageBoxButtons.OK, MessageBoxIcon.Information)
con2.Close()
Me.Server_NameComboBox.SelectedIndex = -1
Me.Database_NameComboBox.SelectedIndex = -1
Me.Database_NameComboBox.Enabled = False
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message)
End Try
End If
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message)
End Try
Prior to restore you should be sure there is no user connected to this database, otherwise you get the error you posted.
You can first set your db offline and then restore:
alter database MyDB set offline
with rollback immediate;
restore database ...
Related
Here is some VB.NET code for backing up our SQL Server 2014 database. When I run the code, the error message shown is "Incorrect syntax error".
Dim sqlcon As New SqlConnection With {.ConnectionString = "Server=USMAN; Database=test; Persist Security Info=True; User ID=sa; Password=123"}
Private Sub btnBackUp_Click(sender As Object, e As EventArgs) Handles btnBackUp.Click
SaveFileDialog1.FileName = DateAndTime.DateString + " - test"
SaveFileDialog1.Filter = "SQL Server database backup files|*.bak"
SaveFileDialog1.ShowDialog()
Dim cmdbak As New SqlCommand("backup database test to disk '" & SaveFileDialog1.FileName & "'", sqlcon)
sqlcon.Open()
cmdbak.ExecuteNonQuery()
MessageBox.Show("Backup has been successfully.")
sqlcon.Close()
End Sub
This is my vb.net code to restore SQL Server database, I think the code does not contain a mistake, so when executing the code it does not appear to be wrong, but it does not restore the database.
Please help me to find the error. I searched a lot online but did not find any solution to the problem.
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
You keep overwriting the query value:
strQuery = "ALTER DATABASE ..."
strQuery = "RESTORE DATABASE ..."
strQuery = "ALTER DATABASE ..."
Will result in the strQuery value only containing the last string. Instead you need to do something like this:
' 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()
I am having a few issues regarding reading data from a local sql server in visual basic. I have made the database and connected it as a data source but for some reason my data source connection and initial catalog must be incorrect. This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = ("Data Source = localhost; Initial Catalog=Database1Dataset; Integrated security=true ")
cmd.Connection = con
con.Open()
cmd.CommandText = "select login, password from Table where login = '" & tboxUname.Text & "' and password = '" & tboxPword.Text & "' "
rd = cmd.ExecuteReader
If rd.HasRows Then
frmProperties.Show()
Else
MsgBox("Incorrect Login") 'Else, display a message saying "incorrect login".
Tries += 1
If Tries = 3 Then
MsgBox("Closing Program")
Close()
End If
End If
End Sub
My database is called Database1 and the table is called Table. Thanks for any help.
I cannot insert records into a SQL Server CE database. I have read lots of articles but I still did not receive a proper answer for that.
This is my code. Database is located in the bin folder of the project.
Dim strConnection As String
strConnection = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\Barcode_UAT.sdf;Persist Security Info=False"
Dim cn As New SqlCeConnection(strConnection)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
Dim cmd As SqlCeCommand
Dim sql As String = "insert into [tbl_Barcodes] ([SerialNo],[ItemId],[Date]) values (#SerialNo,#ItemId,#Date)"
Try
cmd = New SqlCeCommand(sql, cn)
cmd.Parameters.AddWithValue("#SerialNo", "12121333")
cmd.Parameters.AddWithValue("#ItemId", "Item01010")
cmd.Parameters.AddWithValue("#Date", "2012-2-2")
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch sqlexception As SqlCeException
MessageBox.Show(sqlexception.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cn.Close()
End Try
It seems like you are missing the bin folder in your Data Source location path
I am not sure if it's me or there's something wrong with my code. Whenever I try to add a new account, it is being "saved" and shown in my datagridview, however, when I check under the data set or the table data, it's not being saved (or updated). I am using Visual Studio 2013 and I just checked my Microsoft SQL version - 2012. I did what I found here and in other sites, like uncheck the "Prevent saving changes that require table re-creation"; and I also changed the "Copy to output directory to Copy if newer", oh, and I also changed the |DataDirectory| to the path of the 2 mdf files.
Sorry if I'm asking a question that was asked before. And... here's my code (this one is for change password form):
If txtNewPass.Text = txtRetyped.Text Then
Dim strSql As String
Try
Dim objAdap As SqlDataAdapter
Dim objDt As New DataTable
strConn = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FHGES.mdf;Integrated Security=True"
objConn = New SqlConnection(strConn)
Dim s As String = "SELECT * FROM tblAccounts WHERE UName COLLATE Latin1_General_CS_AS='" & frmLogin.txtUname.Text & "'AND PWord COLLATE Latin1_General_CS_AS='" & frmLogin.txtPassword.Text & "';"
objComm = New SqlCommand(s, objConn)
objAdap = New SqlDataAdapter(objComm)
objAdap.Fill(objDt)
lblUName.Text = objDt.Rows(0)(4).ToString
strSql = "UPDATE tblAccounts SET PWord='" & txtRetyped.Text & "' WHERE UName='" & lblUName.Text & "'"
objComm = New SqlCommand(strSql, objConn)
objConn.Open()
objComm.ExecuteNonQuery()
objConn.Close()
MessageBox.Show("Saved new password, please re-login", "FHGES", MessageBoxButtons.OK)
frmLogin.Show()
frmLogin.txtPassword.Clear()
frmLogin.txtPassword.Focus()
Me.Hide()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If objConn.State = ConnectionState.Open Then
objConn.Close()
End If
End Try
Else
MessageBox.Show("Password don't match!", "FHGES", MessageBoxButtons.OK)
txtNewPass.Clear()
txtRetyped.Clear()
txtNewPass.Focus()
End If