2014-10-08 2 views
-1

Я создал систему с функциями резервного копирования и восстановления. Моя резервная копия отлично работает, но моего восстановления нет. Я пробовал это отдельно во всей системе, и он работает. Я уже проверяю, есть ли еще открытые соединения.SQL Restore Database не работает в vb

При восстановлении базы данных сначала мне нужно выбрать все доступные локальные диски. Затем появится другая форма и отобразится все файлы резервной копии внутри выбранного диска.

Вот мой код в frmRestore (Где выбрать диск):

Imports System.IO 
Imports System.Data.SqlClient 

Public Class frmRestore 
Dim con As SqlConnection = New SqlConnection 
Dim cmd As SqlCommand 
Dim dread As SqlDataReader 

Private Sub frmRestore_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing 
    frmMain1.unlockmenu() 
End Sub 

Private Sub frmBackupRestore_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 


    Dim alldrives() As DriveInfo = DriveInfo.GetDrives() 
    For Each d As DriveInfo In alldrives 
     If d.IsReady = True Then 
      ComboBox1.Items.Add(d.Name & " " & d.VolumeLabel) 
     End If 
    Next 

End Sub 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick 
    If ProgressBar1.Value = 100 Then 
     Timer1.Enabled = False 
     ProgressBar1.Visible = False 
     MsgBox("Successfully Done") 
    Else 
     ProgressBar1.Value = ProgressBar1.Value + 5 
    End If 
End Sub 


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim pat As String = ComboBox1.Text & "POSASBACK" 
    If Not System.IO.Directory.Exists(pat) Then 
     MsgBox("No backup files to restore") 
     Exit Sub 
    End If 
    frmRestoreList.Show() 
End Sub 

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 
    Me.Close() 
End Sub 
End Class 

Вот мой код в frmRestoreList (Где выбрать резервные файлы данных):

Imports System.IO 
Imports System.Data.SqlClient 

Public Class frmRestoreList 
Dim con As SqlConnection = New SqlConnection 
Dim cmd As SqlCommand 
Dim dread As SqlDataReader 

Sub query(ByVal que As String) 
    On Error Resume Next 
    cmd = New SqlCommand(que, con) 
    cmd.ExecuteNonQuery() 
    con.Close() 
End Sub 
Private Sub frmRestoreList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

    Dim targetDirectory As String = frmRestore.ComboBox1.Text & "POSASBACK" 
    Dim fileEntries As String() = System.IO.Directory.GetFiles(targetDirectory, "*.bak") 
    Dim filedate As System.IO.FileInfo 
    Dim fileName As String 
    For Each fileName In fileEntries 
     filedate = My.Computer.FileSystem.GetFileInfo(fileName) 
     DataGridView1.Rows.Add(fileName, Replace(fileName, targetDirectory & "\", ""), Format(filedate.LastWriteTime, "MMMM dd,yyyy (dddd)")) 
    Next fileName 

End Sub 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Try 
     If MsgBox("Are you sure you want to proceed with the data file' restore?" & vbNewLine & "This will overwrite your data files in the Back-Up file.", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "") = MsgBoxResult.Yes Then 
      con = New SqlConnection("Data Source=.\SQLEXPRESS;Database=Master;integrated security=SSPI;") 
      con.Open() 
      query("restore database dbbotika FROM DISK='" & DataGridView1.SelectedRows(0).Cells(0).Value & "' with replace") 
     End If 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 

End Sub 
End Class 

Помогите мне, ребята, заранее спасибо.

enter image description here

+0

«Не работает» не является большим для диагностирования проблемы - я заметил, что у вас есть код, который ловит и показывает исключение - это то, что происходит? Если да, то какое сообщение об ошибке отображается? Вы пытались просто запустить SQL в студии управления - работает ли она там? –

+0

Я пробовал это в управлении sql, и он работает. Как то, что я сказал, это часть системы, и когда я ее отделяю и запускаю. Оно работает. – user3579618

ответ

3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
Try 
    If MsgBox("Are you sure you want to proceed with the data file' restore?" & vbNewLine & "This will overwrite your data files in the Back-Up file.", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "") = MsgBoxResult.Yes Then 

     con = New SqlConnection("Data Source=.\SQLEXPRESS;Database=Master;integrated security=SSPI;") 
     con.Open() 

     'Set the DB to the (master) DB => If the used DB was the DB that you want to Restore then an error will occure 
     query("USE [master] ") 

     'Drop the connection to the DB by setting the connection to your session only (single user), any current transaction on the DB => it will be rolledback immediatelly 
     query("ALTER DATABASE dbbotika set SINGLE_USER WITH ROLLBACK IMMEDIATE") 

     'Restore DB 
     query("restore database dbbotika FROM DISK='" & DataGridView1.SelectedRows(0).Cells(0).Value & "' with replace") 

     'Return the connection to the DB to be multi users 
      query("ALTER DATABASE dbbotika SET MULTI_USER") 

     'Use your DB name 
      query("USE [dbbotika] ") 

    End If 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try 

End Sub 
Смежные вопросы