SQL Server Database Backup and Restore in C#

Syed Noman Ali Shah,                          7 Feb 2015                                      CPOL

   3.82 (6 votes)
1

2

3

4

5

3.82/5 - 6 votes
μ 3.82, σa 2.09 [?]
 
Rate:
Add a reason or comment to your vote:             x             Votes of 3 or less require a comment
 
How to take SQL server database backup and database restoration in C# using SMO

Introduction

Developers need to take backup and restore database. Database backup and restore can help you avert disaster. If you backup your files regularly, you can retrieve your information. By taking database backup and restoration through coding, so this could be done via Server Management Objects. So here, I will describe what is SMO and how it will be used for database backup and restoration.

SQL Server Management Objects (also called SMO) is a .NET library which allows you to access and manage all objects of the Microsoft SQL Server.SMO supports SQL Server 2000, 2005 and 2008, 2012. All functions available in SQL Server Management Studio are available in SMO but SMO includes several more features than Management Studio.

Background

You will have to create DSN for connection.

Before coding, you must set the reference to the SMO assembly. You need to add these components:

  1. Microsoft.SqlServer.Smo
  2. Microsoft.SqlServer.SmoExtended
  3. Microsoft.SqlServer.ConnectionInfo
  4. Microsoft.SqlServer.Management.Sdk.Sfc

After Adding References, you need to add 2 using statements:

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

Using the Code

The following code creates connection with SQL Server. To execute:

"select * from sys.databases"

The above query retrieves all databases from SQL Server.

public void Createconnection()
{
DBbackup.DataBaseClass dbc = new DataBaseClass(); cbservername.Properties.Items.Clear();
// select * from sys.databases getting all database name from sql server
cmd = new OdbcCommand("select * from sys.databases", dbc.openconn());
dr = cmd.ExecuteReader();
while (dr.Read())
{
cbdatabasename.Properties.Items.Add(dr[0]);
}
dr.Close();
}

The following code gets server names that exist. To execute:

"select *  from sys.servers"

The above query retrieves servers:

        public void serverName()
{
DBbackup.DataBaseClass dbc = new DataBaseClass();
// select * from sys.servers getting server names that exist
cmd = new OdbcCommand("select * from sys.servers", dbc.openconn());
dr = cmd.ExecuteReader();
while (dr.Read())
{
cbservername.Properties.Items.Add(dr[1]);
}
dr.Close();
}

Database Backup

  public void blank(string str)
{
if (string.IsNullOrEmpty(cbservername.Text) | string.IsNullOrEmpty(cbdatabasename.Text))
{
XtraMessageBox.Show("Server Name & Database can not be Blank");
return;
}
else
{
if (str == "backup")
{
saveFileDialog1.Filter = "Text files (*.bak)|*.bak|All files (*.*)|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// the below query get backup of database you specified in combobox
query("Backup database " + cbdatabasename.Text +
" to disk='" + saveFileDiaog1.FileName + "'"); XtraMessageBox.Show("Database BackUp has been created successful.");
}
}
}
}

Database Restore

 public void Restore(OdbcConnection sqlcon, string DatabaseFullPath, string backUpPath)
{
using (sqlcon)
{
string UseMaster = "USE master";
OdbcCommand UseMasterCommand = new OdbcCommand(UseMaster, sqlcon);
UseMasterCommand.ExecuteNonQuery();
// The below query will rollback any transaction which is
running on that database and brings SQL Server database in a single user mode.
string Alter1 = @"ALTER DATABASE
[" + DatabaseFullPath + "] SET Single_User WITH Rollback Immediate";
OdbcCommand Alter1Cmd = new OdbcCommand(Alter1, sqlcon);
Alter1Cmd.ExecuteNonQuery();
// The below query will restore database file from disk where backup was taken ....
string Restore = @"RESTORE DATABASE
[" + DatabaseFullPath + "] FROM DISK = N'" +
backUpPath + @"' WITH FILE = 1, NOUNLOAD, STATS = 10";
OdbcCommand RestoreCmd = new OdbcCommand(Restore, sqlcon);
RestoreCmd.ExecuteNonQuery();
// the below query change the database back to multiuser
string Alter2 = @"ALTER DATABASE
[" + DatabaseFullPath + "] SET Multi_User";
OdbcCommand Alter2Cmd = new OdbcCommand(Alter2, sqlcon);
Alter2Cmd.ExecuteNonQuery();
Cursor.Current = Cursors.Default;
}
}

Conclusion

This code uses the SQL Server 2005, 2012 backup/restore facility. The code follows the rules of SQL Server 2005, 2012 while backing up or restoring database.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

SQL Server Database Backup and Restore in C#的更多相关文章

  1. [转]Configure Network Drive Visible for SQL Server During Backup and Restore Using SSMS

    本文转自:https://mytechmantra.com/LearnSQLServer/Configure-Network-Drive-Visible-for-SQL-Server-During-B ...

  2. 转载:Restore SQL Server database and overwrite existing database

    转载自:https://www.mssqltips.com/sqlservertutorial/121/restore-sql-server-database-and-overwrite-existi ...

  3. SQL Server 2014 Backup Encryption

    转载自: Microsoft MVP Award Program Blog 来源:Microsoft MVP Award Program Blog 的博客:https://blogs.msdn.mic ...

  4. P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1

    P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1       May ...

  5. Create a SQL Server Database on a network shared drive

    (原文地址:http://blogs.msdn.com/b/varund/archive/2010/09/02/create-a-sql-server-database-on-a-network-sh ...

  6. How to Kill All Processes That Have Open Connection in a SQL Server Database[关闭数据库链接 最佳方法] -摘自网络

    SQL Server database administrators may frequently need in especially development and test environmen ...

  7. Visual Studio 2012创建SQL Server Database Project提示失败解决方法

    新建一个SQL Server Database Project,提示: Unable to open Database project This version of SQL Server Data ...

  8. SQL Server database mail问题诊断一例

    产品环境sql server database的mail发不出邮件,影响客户的业务,在数据库中进行诊断 诊断sql: EXEC msdb.dbo.sp_send_dbmail @profile_nam ...

  9. SQL Server database – Error 3743

    Database mirroring must be removed before you drop SQL Server database – Error 3743 If you try to dr ...

随机推荐

  1. Struts2 用过滤器代替了 servlet ,???? 且不需要tomcat就可以直接做功能测试

    Struts2  用过滤器代替了 servlet ,????  且不需要tomcat就可以直接做功能测试

  2. xhtml html

    xhtml是用xml语言重写了html,相比html更规范了, XHTML是HTML像XML的一个过渡语言,它比HTML严谨性会高点,然后基本语言都还是沿用的HTML的标签,只不过废除了部分表现层的标 ...

  3. Arcgis for Javascript之featureLayer图和属性的互操作

    说明:主要实现加载FeatureLayer与显示属性表,并实现属性表与地图的联动,首先,看看实现后的效果: 显示效果 如上图所示,本文章主要实现了以下几个功能:1.FeatureLayer属性表的分页 ...

  4. WEKA中的数据预处理

    数据预处理包括数据的缺失值处理.标准化.规范化和离散化处理. 数据的缺失值处理:weka.filters.unsupervised.attribute.ReplaceMissingValues. 对于 ...

  5. C#调用EasyPusher推送到EasyDarwin实现视频流中转

    本文转自:http://www.cnblogs.com/kangkey/p/6772863.html 最近在公司项目中,遇到需要将内网的监控视频信息,在外网进行查看,最终通过查阅资料,发现EasyDa ...

  6. VMware Workstation/Fusion 14/15 密钥

    VMware WorkStation 14 CG54H-D8D0H-H8DHY-C6X7X-N2KG6 ZC3WK-AFXEK-488JP-A7MQX-XL8YF AC5XK-0ZD4H-088HP- ...

  7. Python解析excel文件并存入sqlite数据库

    最近由于工作上的需求 需要使用Python解析excel文件并存入sqlite 就此做个总结 功能:1.数据库设计 建立数据库2.Python解析excel文件3.Python读取文件名并解析4.将解 ...

  8. [转]Socket编程中,阻塞与非阻塞的区别

    阻塞:一般的I/O操作可以在新建的流中运用.在服务器回应前它等待客户端发送一个空白的行.当会话结束时,服务器关闭流和客户端socket.如果在队列中没有请示将会出现什么情况呢?那个方法将会等待一个的到 ...

  9. HDU - 5088: Revenge of Nim II (问是否存在子集的异或为0)

    Nim is a mathematical game of strategy in which two players take turns removing objects from distinc ...

  10. PS基础教程[6]如何快速制作一寸照片

    一寸照片使我们经常会用到的,很多的证件照都是使用一寸的照片作为存档的.写这个经验也是因为刚刚有网友求助做一寸照片,所以就顺便写个经验.废话不多说了,进入正题,PS基础教程之快速制作一寸的照片. 制作方 ...