Hi,
I thought when you use "using", it opens and closes the database connection when needed automatically. I am not sure if I am doing this right but would like to know if you can advise if it can be improved. I am able to create the BAK file without issue and I do not get any errors. Thanks.
vb Code:
Private Sub RibbonGroup_SupportSpaceTools_DatabaseManagement_BackupDatabase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RibbonGroup_SupportSpaceTools_DatabaseManagement_BackupDatabase.Click With diagBackupDB .AddExtension = True .CheckFileExists = True .CheckPathExists = True .CreatePrompt = True .DefaultExt = "bak" .DereferenceLinks = True .FileName = "DatabaseBackup" .Filter = "BAK Files|*.bak" .FilterIndex = 1 .InitialDirectory = "C:\" .OverwritePrompt = True .RestoreDirectory = True .Title = ProductName & ": Database Backup" .ValidateNames = True .ShowDialog() If CBool(Windows.Forms.DialogResult.OK) Then Try Using SetDatabaseConnection As New SqlConnection(GetDatabaseConnectionString) 'Specify the SQL query to backup the database. Dim sSQL As String = "BACKUP DATABASE SupportSpace" & vbNewLine & _ "TO DISK = " & "'" & .FileName.ToString & "'" & vbNewLine & _ "WITH FORMAT" Dim sSQLCommand As New SqlCommand SetDatabaseConnection.Open() With sSQLCommand .Connection = SetDatabaseConnection .CommandText = sSQL .ExecuteNonQuery() End With SetDatabaseConnection.Close() End Using 'Everything went ok, advise the end user. MessageBox.Show("The database: SupportSpace was successfully backed up to: " & vbNewLine & vbNewLine & _ .FileName.ToString, _ "Database Backed Up", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information, _ MessageBoxDefaultButton.Button1) Catch ex As InvalidOperationException MessageBox.Show(ex.Message, _ "Invalid Operation Exception", _ MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation, _ MessageBoxDefaultButton.Button1) Catch ex As SqlException MessageBox.Show(ex.Message, _ "SQL Exception", _ MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation, _ MessageBoxDefaultButton.Button1) End Try End If End With End Sub




Reply With Quote