错误:“服务器'MONO-PC \ SQLEXPRESS'的分离数据库失败。”
Public Sub bk()
Try
Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf")
Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC_log.ldf")
' DB.Connection can be any valid SQLConnection which you might already be using in your application
Dim con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
Dim srvCon As New ServerConnection(con)
Dim srv As Server = New Server(srvCon)
If srv.Databases.Contains(strDatabasePath) Then
If Not con.State = ConnectionState.Closed Then
con.Close()
End If
srv.DetachDatabase(strDatabasePath, True)
My.Computer.FileSystem.CopyFile(strDatabasePath, "c:\backup\LIC.mdf", True)
My.Computer.FileSystem.CopyFile(strdbLogPath, "c:\backup\LIC_log.ldf", True)
MessageBox.Show("Backup taken successfully")
End If
srvCon.Disconnect()
con.Open()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
为什么会失败?感谢任何帮助。
答案 0 :(得分:1)
您不应该使用数据库名称的路径,而应从数据库对象中提取文件名。这是一个适用于任何数据库的重写:
Public Sub bk()
Try
Using con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
Dim sDatabaseName As String
con.Open()
sDatabaseName = con.Database
con.Close()
Dim srvCon As New ServerConnection(con)
Dim srv As Server = New Server(srvCon)
If srv.Databases.Contains(sDatabaseName) Then
Dim oDatabase As Database
Dim cFiles As New List(Of String)
' Get a local reference to the database
oDatabase = srv.Databases(sDatabaseName)
' Collect the list of database files associated with this database
For Each oFileGroup As FileGroup In oDatabase.FileGroups
For Each oFile As DataFile In oFileGroup.Files
cFiles.Add(oFile.FileName)
Next
Next
' And collect the list of log files associated with this database
For Each oFile As LogFile In oDatabase.LogFiles
cFiles.Add(oFile.FileName)
Next
' Ensure nothing is using the database
srv.KillAllProcesses(sDatabaseName)
' Detach the database
srv.DetachDatabase(sDatabaseName, False)
' And finally, copy all of the files identified above to the backup directory
For Each sFileName As String In cFiles
System.IO.File.Copy(sFileName, System.IO.Path.Combine("c:\backup\", System.IO.Path.GetFileName(sFileName)), True)
Next
MessageBox.Show("Backup taken successfully")
End If
srvCon.Disconnect()
End Using
Catch ex As Exception
MessageBox.Show("Error Occured : " & ex.Message)
End Try
End Sub