asp.net C # database backup and restore two methods (SQL Server)

Source: Internet
Author: User
Tags mssql server

ASP tutorial. NET C # Database tutorial backup and restore two methods (SQL Server)
The following is mainly about using C # to back up the MSSQL server database. Look at the code below,

Backup methods
///
SqlConnection conn = new SqlConnection ("server=.; Database=master;user Id=sa;password=sa; ");

SqlCommand cmdbk = new SqlCommand ();
Cmdbk.commandtype = CommandType.Text;
Cmdbk.connection = conn;
Cmdbk.commandtext = @ "BACKUP database test to disk= ' C:ba ' with Init";

Try
{
Conn.Open ();
Cmdbk.executenonquery ();
MessageBox.Show ("Backup successed.");
}
catch (Exception ex)
{
MessageBox.Show (Ex.message);
}
Finally
{
Conn.close ();
Conn.dispose ();
}


///
///Restore method
///
sqlconnection   conn   =   new   Sqlconnec tion ("server=.; database=master;user   Id=sa;password=sa;trusted_connection=false ");
Conn.Open ();

//kill   database   Process
sqlcommand   cmd   =   New    SqlCommand ("select   spid   from   sysprocesses  , sysdatabases   where   sysprocesses.dbid=sysdatabases.dbid   and   Sysdatabases.name= ' Test ' ",   conn);
 
sqldatareader   Dr;
dr   =   cmd.executereader ();
arraylist   list   =   new   ArrayList ();
while (Dr.read ())
{
List.add (dr.getint16 (0));
}
Dr.close ();
for (int   i   =   0;   i   <   list.count; & nbsp i++)
{
cmd   =   new   SqlCommand (String.Format ("kill   {0}",  & nbsp list),   conn);
Cmd.executenonquery ();
}

SqlCommand cmdrt = new SqlCommand ();
Cmdrt.commandtype = CommandType.Text;
Cmdrt.connection = conn;
Cmdrt.commandtext = @ "RESTORE database test from disk= ' C:ba '";

Try
{
Cmdrt.executenonquery ();
MessageBox.Show ("Restore successed.");
}
catch (Exception ex)
{
MessageBox.Show (Ex.message);
}
Finally
{
Conn.close ();
}

Method Two

(Implement database backup restore operation with SQL statement

To back up the SQL Server database:
Backup database name to disk (back up file Store path + filename). bak

To restore the SQL Server database:
string path = This.fileupload1.postedfile.filename; Get backup path and database name
Use master Restore database name from disk= ' "+ Path +" ' "; )


using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using System.Collections;
Using System.data.sql;
Using System.IO;


Namespace Database backup
{
public partial class Form1:form
{
You need to add a reference to the Sqldmo.dll under C:Program FilesMicrosoft SQL Server80toolsbinn;
SQL default installation is on the path above
The backed up files are placed under C:Program FilesMicrosoft SQL Servermssqlbackup
string servername = "";
string username = "sa";//temporarily locked, can be set on your own
string password = "sa";

Public Form1 ()
{
InitializeComponent ();

}
Get Server List
Public ArrayList getserverlist ()
{
ArrayList alservers = new ArrayList ();

Sqldmo.application Sqlapp = new Sqldmo.applicationclass ();
Try
{
Sqldmo.namelist serverlist = Sqlapp.listavailablesqlservers ();
for (int i = 1; I <= serverlist.count; i++)
{
Alservers.add (Serverlist.item (i));
Combobox1.items.add (Serverlist.item (i));
Listbox1.items.add (Serverlist.item (i));

}
}
catch (Exception e)
{
Throw (New Exception ("Fetch database server List error:" + e.message));
}
Finally
{
Sqlapp.quit ();
}
return alservers;
}
Get a list of databases
Public ArrayList getdblist (String strservername, String strUserName, String strpwd)
{
string servername = strServerName;
string username = strUserName;
string password = strpwd;

ArrayList Aldbs = new ArrayList ();
Sqldmo.application Sqlapp = new Sqldmo.applicationclass ();
Sqldmo.sqlserver svr = new Sqldmo.sqlserverclass ();
Try
{
Svr.connect (servername, username, password);
foreach (Sqldmo.database db in svr.databases)
{
if (db.name!= null)
Aldbs.add (Db.name);
Listbox2.items.add (Db.name);
}
}
catch (Exception e)
{
MessageBox.Show ("Connection Database error:" + e.message);
}
Finally
{
Svr.disconnect ();
Sqlapp.quit ();
}
return Aldbs;
}
Backing up data
public bool BackupDB (string strDbName, String strFileName, ProgressBar pgbmain)
{
ProgressBar pbar = Pgbmain;
Sqldmo.sqlserver svr = new Sqldmo.sqlserverclass ();
Try
{
Svr.connect (servername, username, password);
Sqldmo.backup bak = new Sqldmo.backupclass ();
bak.action = 0;
Bak.initialize = true;
Sqldmo.backups Tutorial Ink_percentcompleteeventhandler Pceh = new Sqldmo.backupsink_percentcompleteeventhandler (step);
Bak.percentcomplete + = PCEH;
Bak.files = strfilename;//Here can be written as path + filename form, write yourself!
Bak.database = strDbName;
Bak.sqlbackup (SVR);
return true;
}
catch (Exception err)
{
Throw (New Exception ("Backup database Failed" + err.message));
}
Finally
{
Svr.disconnect ();
}
}
Progress bar
private void Step (string message, int percent)
{
Pbar.visible = true;
Pbar.value = percent;
}

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.