2017-06-13 49 views
0

我想在我的应用程序中创建备份和恢复功能。现在,我有这段代码。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. 

从那里我卡住了。我该怎么办?

+0

为什么不只是复制数据库文件当备份和恢复?您仍然可以在复制时指定文件名称。 –

+0

我打算让它成为一个.bak文件,而不是真的复制数据库文件。如果我这样做,那么人们如何做到这一点? – NoobCoder

回答

1

复制文件(下面的代码允许覆盖现有文件):

System.IO.File.Copy(existing file path here, destination file path here, True) 

记住,你可以给文件中的任何文件扩展名,你想如:

System.IO.File.Copy(C:\abc.accdb, C:\Backup\abc.db123, True) 

另外,看看这个:

Copy Data from a table in one Database to another separate database

+0

我得到一个错误,说数据库正在使用中。我应该如何停止使用VB.NET的过程?顺便说一下MSSQLLocalDb。 – NoobCoder