我正在尝试在我的应用程序中创建备份和还原功能。现在,我有这段代码。
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.
从那里我被卡住了。我该怎么办?
答案 0 :(得分:1)
复制文件(下面的代码允许覆盖现有文件):
disposable.isDisposed()
请记住,您可以为文件提供所需的任何文件扩展名,例如:
System.IO.File.Copy(existing file path here, destination file path here, True)
另外,看看这个:
Copy Data from a table in one Database to another separate database