SQL Server Database Backup and Restore in C#
SQL Server Database Backup and Restore in C#
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:
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SmoExtended
Microsoft.SqlServer.ConnectionInfo
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#的更多相关文章
- [转]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 ...
- 转载:Restore SQL Server database and overwrite existing database
转载自:https://www.mssqltips.com/sqlservertutorial/121/restore-sql-server-database-and-overwrite-existi ...
- SQL Server 2014 Backup Encryption
转载自: Microsoft MVP Award Program Blog 来源:Microsoft MVP Award Program Blog 的博客:https://blogs.msdn.mic ...
- 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 ...
- 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 ...
- 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 ...
- Visual Studio 2012创建SQL Server Database Project提示失败解决方法
新建一个SQL Server Database Project,提示: Unable to open Database project This version of SQL Server Data ...
- SQL Server database mail问题诊断一例
产品环境sql server database的mail发不出邮件,影响客户的业务,在数据库中进行诊断 诊断sql: EXEC msdb.dbo.sp_send_dbmail @profile_nam ...
- SQL Server database – Error 3743
Database mirroring must be removed before you drop SQL Server database – Error 3743 If you try to dr ...
随机推荐
- c#的DateTime.Now详解
(转自:http://www.cnblogs.com/lida/archive/2011/01/02/1924197.html) //2008年4月24日 System.DateTime.Now.To ...
- web前端概念摘要(一)
1.前端不必等后端开发完成后才开发的情况:(1)前后端分离:前后端工程不在同一工程目录,前端专注页面样式与效果开发,设计数据展示等问题,可自行建立假数据或本地数据文件测试.后期联调再做修改,修改前端人 ...
- linux时间管理 之 jiffies
1.jiffies 又称时钟滴答,是一个全局变量,它的值在系统引导的时候初始化为0,在时钟中断初始化完成后,每次时钟中断发生,在时钟中断处理例程中都会将jiffies的值 +1. jiffies_64 ...
- Every derived table must have its own alias
完整错误信息如下: Every derived table must have its own alias 三月 28, 2017 10:20:46 上午 org.apache.catalina.co ...
- 从微软官网下载VS离线安装包的方法
这里描述是包括所有版本,截图以下载VS2017社区版为例: ①登入VS官网下载页面,选择需要的版本点击下载,下载页点此进入. ②下载完成后,打开下载文件所在文件夹,Windows 8.1及以上版本用户 ...
- Django 之Ajax
必备知识:json 什么是json 定义 JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式. 它基于 ECMAScript (w3c制定的 ...
- 简述Java面向对象三大特征:封装、继承、多态
封装: 把对象的全部属性和服务结合在一起,形成不可分割的独立单位: 尽可能隐藏内部细节.(数据隐藏.隐藏具体实现的细节) public.private.protected.default pu ...
- ActiveMQ之ActiveMQ-CPP安装及测试
在介绍ActiveMQ-CP之前,先介绍下CMS(C++ Messaging Service),CMS是C++程序与消息中间件进行通信的一种标准接口,可以通过CMS接口与类似ActiveMQ这样的消息 ...
- SQLmap是一款用来检测与利用SQL漏洞的注入神器。
sqlmap 重要参考 http://www.kali.org.cn/forum-75-1.html SQLmap是一款用来检测与利用SQL漏洞的注入神器.开源的自动化SQL注入工具,由Python写 ...
- 图解Fiddler如何抓手机APP数据包过滤抓取
使用fidder抓取浏览器的包相信不是问题,那么使用fidder 抓取app的数据包呢??? 于是,找了一篇博客来学习一下,可以参考一下,根据自己的需求来实现. 在网上自己学习,然后整理了我所用到的, ...