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

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

问题描述

我如何使用一个.bak的数据库备份文件(通过 SQL&NBSP查询备份,服务器)编程?

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

我想我的应用程序到我的数据库备份到一个位置(我已经可以做),我也希望它能够加载已备份的数据库(.bak文件)。

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).

我怎么可以这样使用C#?

How can I do this using C#?

推荐答案

您需要首先确保您有SMO(SQL Server管理对象)安装,可供您在开发框。这就是典型的例子,如果你已经安装了SQL Server的一些版本就可以了。

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.

如果您有SMO库中可用,您可以使用此代码段为您的操作

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

和命名空间 Microsoft.SqlServer.SmoExtended 被称为装配实施 Microsoft.SqlServer.SmoExtended.dll 应在目录中找到 C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\ 如果你有安装SMO。

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.

如果您尚未安装SMO,你可以去从的这里 SQL Server 2008或的这里的SQL Server 2008 R2(也有SQL Server 2005的一个旧版本)

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天全站免登陆