1. 程式人生 > >資料庫的備份與還原(vb.net程式碼篇)

資料庫的備份與還原(vb.net程式碼篇)

        在資料庫中我們既可以手動的進行備份與還原,也可通過sql語句進行備份與還原。也可以根據需求設定成自動在規定的時間內進行自動備份。但是對於一般的系統使用者來說直接進入比較陌生的資料庫來進行設定則顯得不是很友好,所以通過程式碼來實現只需利用控制元件進行簡單的操作則顯得很重要

資料庫備份

       說明:可以將資料庫備份到指定的位置,如不指定則預設到資料庫的安裝資料夾內,為了還原方便在命名是加上了時間。

<strong><span style="font-size:18px;">        Dim cn As SqlConnection  '定義一個連結物件
        Dim cm As SqlCommand     '定義一個命令物件
        Dim all1 As String       '用來存放需要備份的資料庫的備份時的名字
        all1 = "d:\HumanResourcesSystem" & Format(Now, "yy-MM-dd")   '指定備份的路徑和名字,在這裡加了一個時間
        cn = New SqlConnection("Data Source=.;Initial Catalog=HumanResourcesSystem;User ID=sa;Password=123456")  '給物件賦值
        cm = New SqlCommand("BACKUP DATABASE HumanResourcesSystem TO DISK='" & all1 & "' WITH Format", cn)    '通過使用WITH FORMAT可以做到覆蓋任何現有的備份和建立一個新的媒體集
        cn.Open()   '開啟資料庫
        cm.ExecuteNonQuery()
        MsgBox("備份成功,請到D盤查詢")
        cn.Close()</span></strong>

資料庫的還原

        說明:進行還原時由使用者自行選擇要還原的資料庫

<strong><span style="font-size:18px;">        Dim cn As New SqlConnection        '定義一個連結物件
        Dim cn1 As New SqlConnection       '在定義一個連結物件
        Dim mydr As SqlDataReader          '定義一個讀取資料的物件</span></strong>
<strong><span style="font-size:18px;">        Dim str As String                  '定義一個字元用來盛放資料庫程序
        Dim tmpConnectionString As String = "Data Source= LJM;Initial Catalog=master;Integrated Security=True"   '將連結語句賦值給tmpconnectionstring
        Dim all As String
        Me.OpenFileDialog1.Filter = "所有檔案(*.*)|*.*|備份檔案(*.bak)|*.bak"   '開啟選擇框進行選擇
        Me.OpenFileDialog1.ShowDialog()
        all = OpenFileDialog1.FileName    '獲得檔名
        If all = Nothing Then
            MessageBox.Show("檔名不能為空", "系統提示")
            Exit Sub
        End If
        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('HumanResourcesSystem')", cn)  '選擇所有程序
        mydr = cm.ExecuteReader()
        Dim cm1 As SqlCommand = New SqlCommand()
        cm1.Connection = cn1
        While (mydr.Read())   '殺死程序
            str = mydr("spid").ToString()
            cm1.CommandText = str
            cm1.CommandType = CommandType.Text
            Application.DoEvents()
            cm1.ExecuteNonQuery()

        End While
        mydr.Close()
        cm = New SqlCommand("RESTORE DATABASE HumanResourcesSystem FROM DISK='" & all & "'WITH REPLACE", cn)   
        cm.ExecuteNonQuery()
        MsgBox("恢復自" & all & ",軟體自動關閉,請重新啟動")
        cn.Close()
        cn1.Close()
        Me.Close()</span></strong>

總結:這兩個功能還有很多可以完善之處,但功能已經能實現