這是我的數據備份和恢復模塊
Option Explicit
Public conn As New ADODB.Connection '數據庫連接變量
Private WithEvents objBackup As SQLDMO.Backup
Private WithEvents objRestore As SQLDMO.Restore
Public isql As String
Private Sub cmdBackup_Click() '備份按鈕
Dim objSQLServer As New SQLDMO.SQLServer
Dim strServer As String
Dim strUserID As String
Dim strPassword As String
Dim strDatabase As String
Dim strFile As String
strServer = "127.0.0.1"
strUserID = "sa"
strPassword = ""
strDatabase = "lifei"
strFile = App.Path & "\數據備份\bak"
If Dir(strFile) <> "" Then
If MsgBox("文件" & strFile & "已存在,是否刪除?", vbQuestion + vbYesNo) = vbYes Then
Kill strFile
Else
Exit Sub
End If
End If
lblProgress.Caption = "備份進度: 0%"
Screen.MousePointer = 11
On Error GoTo ErrorHandler
objSQLServer.Connect strServer, strUserID, strPassword
Set objBackup = New SQLDMO.Backup
With objBackup
.PercentCompleteNotification = 1
.Database = strDatabase
.Files = strFile
.SQLBackup objSQLServer
End With
Set objBackup = Nothing
objSQLServer.Close
Set objSQLServer = Nothing
Screen.MousePointer = 0
Exit Sub
ErrorHandler:
Screen.MousePointer = 0
MsgBox Err.Description, vbCritical
End Sub
Private Sub cmdRestore_Click()
Dim objSQLServer As New SQLDMO.SQLServer
Dim strServer As String
Dim strUserID As String
Dim strPassword As String
Dim strDatabase As String
Dim strFile As String
strServer = "127.0.0.1"
strUserID = "sa"
strPassword = ""
strDatabase = "lifei"
strFile = App.Path & "\數據備份\bak"
If Dir(strFile) = "" Then
MsgBox "文件" & strFile & "不存在!", vbExclamation
Exit Sub
End If
lblProgress.Caption = "恢復進度: 0%"
Screen.MousePointer = 11
On Error GoTo ErrorHandler
objSQLServer.Connect strServer, strUserID, strPassword
Set objRestore = New SQLDMO.Restore
With objRestore
.PercentCompleteNotification = 1
.Database = strDatabase
.ReplaceDatabase = True
.Files = strFile
.SQLRestore objSQLServer
End With
Set objRestore = Nothing
objSQLServer.Close
Set objSQLServer = Nothing
Screen.MousePointer = 0
Exit Sub
ErrorHandler:
Screen.MousePointer = 0
MsgBox Err.Description, vbCritical
End Sub
Private Sub Command1_Click()
Unload Me
End Sub
Private Sub Form_Unload(Cancel As Integer)
If conn.State <> 0 Then
conn.Close
Set conn = Nothing
End If
End Sub
Private Sub objBackup_Complete(ByVal Message As String)
lblProgress.Caption = "備份成功!"
Set objBackup = Nothing
End Sub
Private Sub objBackup_PercentComplete(ByVal Message As String, ByVal Percent As Long)
lblProgress.Caption = "備份進度: " & Percent & "%"
DoEvents
End Sub
Private Sub objRestore_Complete(ByVal Message As String)
lblProgress.Caption = "恢復成功!"
Set objRestore = Nothing
End Sub
Private Sub objRestore_PercentComplete(ByVal Message As String, ByVal Percent As Long)
lblProgress.Caption = "恢復進度: " & Percent & "%"
DoEvents
End Sub