以编程方式使用备份数据库 [英] Using backup database programmatically

查看:130
本文介绍了以编程方式使用备份数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用.bak数据库备份文件(通过适用于SQL Server 2008或这里为SQL Server 2008 R2(也有SQL Server 2005的一个旧版本)


How can I use a .bak database backup file (backed up via a query in SQL Server) programmatically?

I want my application to back up my database to a location (which I can already do) and I also want it to be able to load a backed up database (the .bak file).

How can I do this using C#?

解决方案

You need to first make sure you have the SMO (SQL Server Management Objects) installed and available to you on your dev box. This is typically the case, if you have installed some version of SQL Server on it.

If you have the SMO library available, you can use this code snippet for your operation:

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

static void Main(string[] args)
{
    // create instance of SMO Server object
    Server myServer = new Server("(local)");

    // create new instance of "Restore" object    
    Restore res = new Restore();
    res.Database = "SMO";  // your database name

    // define options       
    res.Action = RestoreActionType.Database;
    res.Devices.AddDevice(@"C:\SMOTest.bak", DeviceType.File);
    res.PercentCompleteNotification = 10;
    res.ReplaceDatabase = true;

    // define a callback method to show progress
    res.PercentComplete += new PercentCompleteEventHandler(res_PercentComplete);

    // execute the restore    
    res.SqlRestore(myServer);
 }

 // method to show restore progress
 static void res_PercentComplete(object sender, PercentCompleteEventArgs e)
 {
    // do something......
 }

For this to work, you need to have the following project references

and the namespace Microsoft.SqlServer.SmoExtended is implemented in the assembly called Microsoft.SqlServer.SmoExtended.dll which should be found in the directory C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\ if you have SMO installed.

If you don't have SMO installed, you can go fetch it from here for SQL Server 2008 or here for SQL Server 2008 R2 (there's also an older version for SQL Server 2005)

这篇关于以编程方式使用备份数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆