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

最新文章

  1. MySQL mysqlslap压测
  2. 理清C++常量指针和指针常量这团乱麻
  3. 教你如何快速下载旧版本的Firefox浏览器
  4. windows进程通信 -- WM_COPYDATA消息
  5. 对比DOM和jQuery完善度
  6. cisco交换技术list
  7. c++ builder xe2 (Embarcadero rad studio) 远程调试 同样适用于 delphi 远程调试 教程
  8. Mobile Web 调试指南(2):远程调试
  9. UVA 10341 二分搜索
  10. Tachyon框架的Worker心跳及Master高可用性分析
  11. Guava文档翻译之 Guava简介
  12. PHP中的变量
  13. WinForm触摸屏程序功能界面长时间不操作自动关闭回到主界面 z
  14. HDU 3427
  15. Windows Server 2012 在个人终端上使用的推荐设置
  16. 从Dynamics CRM2011到Dynamics CRM2016的升级之路
  17. Python解析XML文件
  18. 使用js下载文件
  19. swift - xcode10 - 点击事件交互BUG - (手势和button的addTarget方法)
  20. SharpDevelop 笔记

热门文章

  1. java继承的一些问题
  2. linux文件组、权限等
  3. 小晚wan的公众号
  4. 前端基础之jQuery入门 01
  5. vector释放内存之swap方法
  6. kali视频学习(6-10)
  7. LA3263 That Nice Euler Circuits
  8. LG3648 [APIO2014]序列分割
  9. Log4j日志配置说明
  10. [转]javascript中基本类型和引用类型的区别分析