如何用VB.net实现sql数据库的备份与恢复

来源:设计前沿 作者:佚名 时间:2008-12-04

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click '备份数据库 'BACKUP DATABASE Test TO DISK='C:\Backup' WITH Format Dim cn As SqlConnection Dim cm As SqlCommand cn = getDB() cm = New SqlCommand("BACKUP DATABASE JXbase TO DISK='C:\Backup ' WITH Format", cn) cn.Open() cm.ExecuteNonQuery() MsgBox("备份成功") cn.Close()

End Sub

'恢复 Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click Dim cn As New SqlConnection Dim cn1 As New SqlConnection Dim mydr As SqlDataReader Dim str As String

Dim tmpConnectionString As String = "Data Source=JJK;Initial Catalog=master;Integrated Security=True" cn.ConnectionString = tmpConnectionString cn1.ConnectionString = tmpConnectionString cn.Open() cn1.Open() Dim cm As SqlCommand = New SqlCommand("select spid from master..sysprocesses where dbid=db_id('JXbase')", cn) mydr = cm.ExecuteReader()

Dim cm1 As SqlCommand = New SqlCommand() cm1.Connection = cn1

While (mydr.Read()) '杀死进程

str = "kill " & mydr("spid").ToString() cm1.CommandText = str cm1.CommandType = CommandType.Text Application.DoEvents() cm1.ExecuteNonQuery() '杀进程 End While mydr.Close() cm = New SqlCommand("RESTORE DATABASE JXbase FROM DISK='C:\Backup'", cn) '恢复备份 cm.ExecuteNonQuery() MsgBox("恢复成功成功") cn.Close() cn1.Close()

End Sub