Thursday, April 7, 2011

How to backup database SQL SERVER from VB NET?

Besides using SQL-DMO as Suprotim said, you also can use SQL commands to backup and restore SQL Server database.
Code Block
Imports System.Data.SqlClient

Public Class Form1

    Dim con As SqlConnection
    Dim cmd As SqlCommand

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        con = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=DBNAME")
    End Sub

    ' Backup
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        cmd = New SqlCommand("backup database DBNAME to disk='\\server\path\filename.bak'", con)
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    End Sub

    ' Restore
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        cmd = New SqlCommand("restore database DBNAME from disk='\\server\path\filename.bak'", con)
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    End Sub

End Class
Please check this thread for detail:

1 comment:

  1. in restoring following error comes

    RESTORE cannot process database 'Studio' because it is in use by this session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally.

    ReplyDelete