我想在我的应用程序中创建备份和恢复功能。现在,我有这段代码。MSSQLLocalDb VB.NET中的数据库备份
Dim destdir As String = "C:\Desktop\Backup Database"
Dim dbname As String = "dbOffense"
'Metioned here your database name
Dim con As New SqlConnection(constr)
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable()
'Check that directory already there otherwise create
If Not System.IO.Directory.Exists(destdir) Then
System.IO.Directory.CreateDirectory("C:\Desktop\Backup Database")
End If
Try
'Open connection
con.Open()
'query to take backup database
cmd = New SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", con)
cmd.ExecuteNonQuery()
'Close connection
con.Close()
MessageBox.Show("Backup database successfully")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
,也是我的连接字符串:
<add name="ConString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbOffense.mdf;Integrated Security=True;Connect Timeout=30;"
providerName="System.Data.SqlClient" />
.mdf文件是在项目文件夹并将其设置为Copy If Newer
,如果这是任何帮助。
每当我点击我的应用程序中的备份功能,就会发生错误。它说
dbOffense does not exist
就这样,我尝试添加database=dbOffense
连接字符串,但它说
Unable to attach the .mdf file as database dbOffense because the .mdf file copy in the bin/Debug folder is in use.
从那里我卡住了。我该怎么办?
为什么不只是复制数据库文件当备份和恢复?您仍然可以在复制时指定文件名称。 –
我打算让它成为一个.bak文件,而不是真的复制数据库文件。如果我这样做,那么人们如何做到这一点? – NoobCoder