简体   繁体   中英

Sql Server 2008 R2 Database backup and restore functionality by C# Windows Application

I develop a windows application for a small shop for generating invoices. Now I want to give a functionality for the user to make backup of each day database on a button click from the windows application. Also he should be able to restore the database from these backup.

Please help me i searched many topics but not works. Thanks..

You have to use the using Microsoft.SqlServer.Management.Smo name space and use the BackUp Method provided. It has various backup options. Please See this link

using Microsoft.SqlServer; using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common; using System.Data.SqlClient; using System.Configuration; public void BackupDatabase(string BackUpLocation, string BackUpFileName, string DatabaseName, string ServerName) { DatabaseName = "[" + DatabaseName + "]"; string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ; BackUpFileName = BackUpFileName + fileUNQ + ".bak"; string SQLBackUp = @"BACKUP DATABASE " + DatabaseName + " TO DISK = '" + BackUpLocation + @"\" + BackUpFileName + @"'"; string svr = "Server=" + ServerName + ";Database=" + DatabaseName + ";Integrated Security=True"; SqlConnection cnBk = new SqlConnection(svr); SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk); try { cnBk.Open(); cmdBkUp.ExecuteNonQuery(); //MessageBox.Show("Done"); MessageBox.Show(SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n\nBackUp Date : " + DateTime.Now.ToString()); } catch (Exception ex) { MessageBox.Show(ex.ToString()); //MessageBox.Show(SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + @"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString()); } finally { if (cnBk.State == ConnectionState.Open) { cnBk .Close(); } } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM