MSSQL, C #, Winform, ASP-database backup and restore modules

Source: Internet
Author: User

Database backup Restore class:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks;// Apply the appropriate namespace using system.windows.forms;using system.collections;using system.io;using system.data;using System.data.sqlclient;namespace canyinxt. command{public static class Bacupdatabase {static string connectionString = "Data source= (local); Initial Ca        talog=master;integrated Security = true ";        static SqlConnection conn = new SqlConnection (connectionString); #region back up the specified database file///<summary>//backup the specified database file///</summary>//<param name= "DBName" > Backup name is the same as the database name in the database </param>//<param name= "DatabaseName" > The database to be restored (contains the file name to be backed up) </param >//<returns></returns> public static bool BackupDatabase (string DBName, String Databasefil e) {if (! File.exists (Databasefile)) {}//restored database mydatabase String sql = "BackuP DATABASE "+" "+ DBName +" "+" to DISK = ' "+ databasefile +". Bak "; Conn.            Open ();            SqlCommand comm = new SqlCommand (SQL, conn);            Comm.commandtype = CommandType.Text; try {Comm.            ExecuteNonQuery (); } catch (Exception err) {string str = err.                Message; Conn.                Close ();            return false; } conn.        Close ();//Shutdown database connection return true; #endregion//The following is the restore database, a little more trouble, to shut down all connections to the current database #region restore the database///<summary> Original database///</summary>//<param name= "DBName" > to restore the database name (this name is the same as the backup time) </param>//&lt ;p Aram Name= "backfile" > Database file path (plus name) </param>//<returns></returns> public static bool Restoredatabase (String DBName, String backfile) {///kills all the original database connection processes SqlConnection conn = new SqlcoNnection (); Conn.            ConnectionString = "Data source= (local); Initial catalog=master;integrated security = true"; Conn.            Open (); String sql = "Select spid from sysprocesses, sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid and sysdatabases.            Name= ' + ' + ' + DBName + ' + ' ';            SqlCommand cmd1 = new SqlCommand (SQL, conn);            SqlDataReader Dr;            ArrayList list = new ArrayList (); try {dr = Cmd1.                ExecuteReader (); while (Dr. Read ()) {list. ADD (Dr.                GetInt16 (0)); } Dr.            Close (); } catch (SqlException eee) {MessageBox.Show (eee.            ToString ()); } finally {Conn.            Close (); }//messagebox.show (list.            Count.tostring ()); for (int i = 0; i < list. Count; i++) {Conn.              Open ();  CMD1 = new SqlCommand (string. Format ("KILL {0}", List[i].                ToString ()), conn); Cmd1.                ExecuteNonQuery (); Conn.                Close (); MessageBox.Show ("The system has purged the database thread:" + list[i]. ToString () + "\ r \ n Restoring the database!"            "); } MessageBox.Show ("The system has purged the database thread:" + list.) Count.tostring () + "\ r \ n Restoring the database!"            ");            This must be the master database, not the database to be restored, because it becomes a different process//occupies the database.            string constr = @ "Data source= (local); Initial catalog=master;integrated security = true";            string database = DBName;            string path = Backfile;            String BACKUP = String.Format ("RESTORE database {0} from DISK = ' {1} ' with REPLACE ', DATABASE, Path);            SqlConnection con = new SqlConnection (CONSTR);            SqlCommand cmd = new SqlCommand (BACKUP, con); Con.            Open (); try {cmd.                ExecuteNonQuery (); MessageBox.Show ("Restore successful, click to exit the system, please login again!")                ");         Application.exit ();       return true;                } catch (SqlException ee) {//throw (EE);                MessageBox.Show ("Restore Failed"); MessageBox.Show (EE. ToString () + "Restore failed!" "," Restore failed!                ");            return false; } finally {con.            Close (); }} #endregion}}

Use of Backup methods:

Invoke the BackupDatabase (backup method) under the Bacupdatabase class under the Command folder:

Command.BacupDatabase.BackUpDataBase ("db_cyms", Backuppath + @ "\db_cyms")

Use of the Restore method:

Invoke the Restoredatabase (Restore method) under the Bacupdatabase class under the Command folder:

Command.BacupDatabase.RestoreDatabase ("db_cyms", RestoreDB)

Reference: http://www.cnblogs.com/enjoyprogram/p/3177693.html

MSSQL, C #, Winform, ASP-database backup and restore modules

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.