Monday, 19 March 2018

SQL Server database backup using SQL StoreProcedure in c# winform application

Description : in this post how to take DB backup from winform using SQL Storeprocedure

- Step 1 : Create new sample database for generate backup

Database Name : SampleDBTest

- Step 2 : Create StoreProcedure for generate backup file

CREATE PROC DatabaseBackupProcedure
AS 
BEGIN 

    DECLARE @path Varchar(1000); 

    SET @path='YourDBBackupPath\SampleDBTest'+CONVERT(CHAR(10),  GETDATE(), 121)+'.bak'; 
   
    BACKUP DATABASE SampleDBTest to DISK=@path; 
END 

- Step 3 : Create winform application for call store procedure of database backup

- Step 4 : Get Connection String of SampleDBTest database and add in App.Config file

- Step 5 : Write below c# code in button click for call procedure

Code Note : Get Connection string from App.Config file and add below namespace for get connection string from App.Config and SQL Connection

using System.Data.SqlClient; 
using System.Configuration; 

SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()); 
       
private void btnBackupDB_Click(object sender, EventArgs e) 

    con.Open(); 
    SqlCommand cmd = new SqlCommand("DatabaseBackupProcedure", Connection); 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.ExecuteNonQuery(); 
    con.Close(); 
    MessageBox.Show("Back up Done successfully");
}

Note : By using this code database direct create .bak file in your folder path set in sql storeprocedure

No comments:

Post a Comment