I want to restore a SQL Server localdb database. I tried with this code:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim ofd As New OpenFileDialog() With
{
.Filter = "Backup file | *.bak",
.FileName = ""
}
If ofd.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Cursor = Cursors.WaitCursor
Dim csb = New SqlConnectionStringBuilder("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\CHAKER\Documents\RestoDB.mdf;Integrated Security=True;Connect Timeout=30")
Dim dbFullPath = csb.AttachDBFilename
Dim sql = String.Format("RESTORE DATABASE ""{0}"" From DISK = '{1}'", dbFullPath, ofd.FileName)
Dim cmd As New SqlCommand(sql, con)
cmd.ExecuteNonQuery()
MsgBox("Restore complete")
Cursor = Cursors.Default
End If
End Sub
I get this exception :
RESTORE cannot process database 'C:\Users\CHAKER\Documents\RestoDB.mdf' because it is in use by this session. It is recommended that the master database be used when performing this operation.
You have a number of issues with your code:
AttachDbFileName, and such a database cannot be restored over. UsingAttachDbFileNameis in any case deprecated. You should instead attach it to LocalDB using the normalCREATE DATABASE FOR ATTACHsyntax.Using. Do not cache the connection object.RESTOREcommand, rather than injecting the names directly