'* 名称:BackupDatabase
'* 功能:备份数据库
'* 控件:一个文本框和两个按钮(备份到和确定)
'*********************************************************
Public Sub BackupDatabase()
Dim cn As New ADODB.Connection
Dim s_path, s_dataexport As String
s_path = App.Path
Me.MousePointer = 11 '设置鼠标指针形状
'student1是需要备份的数据库名称
s_dataexport = "backup database student1 to disk='" + CommonDialog1.FileName + "'"
cn.Open "driver={sql server};server=" & d1 & ";database=student1;persist security info=false; userid=sa" '数据库连接字符串
'这里不需要连接master数据库,即可完成备份
cn.BeginTrans
cn.Execute s_dataexport
Err.Number = 0
If Err.Number = 0 Then
cn.CommitTrans
MsgBox "数据备份成功!", vbInformation, "提示"
MsgBox "数据备份文件存放路径:" & CommonDialog1.FileName, vbOKOnly, "提示"
Unload Me
Else
cn.RollbackTrans
MsgBox "数据备份失败!请检查数据库是否正在打开!", vbCritical, "提示"
End If
cn.Close
Set cn = Nothing
Me.MousePointer = 1
End Sub
Private Sub Button_backup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_backup.Click
'执行备份过程
Try
‘备份数据库
Me.backupDb()
MsgBox("数据成功备出!", MsgBoxStyle.OKOnly)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OKOnly)
End Try
End Sub
’备份方法其中backupDir为应用程序中制定备份路径的全局变量,在应用程序启动的时候从配置文件里面读出来的值
Private Sub backupDb()
Dim mysqlcomm As SqlClient.SqlCommand
Dim strsql As String
Dim strbak As String
Try
'判断备份路径参数里面是否制定路径
If backupDir <> Nothing Then
'判断路径是否存在
If Not System.IO.Directory.Exists(backupDir) Then
'创建路径
System.IO.Directory.CreateDirectory(backupDir)
End If
Else
If Not System.IO.Directory.Exists(Application.StartupPath + "\backup") Then
'创建路径
System.IO.Directory.CreateDirectory(Application.StartupPath + "\backup")
End If
backupDir = Application.StartupPath + "\backup"
End If
其实一种很简单的方法就是把数据库文件用程序复制一份就行了.
Cn.Execute "backup database cycd to disk='" & 路径+文件名