如何使用 .bak 数据库备份文件(通过查询备份SQL 服务器)以编程方式?
我希望我的应用程序将数据库备份到某个位置(我已经可以做到),并且我还希望它能够加载备份的数据库(.bak 文件)。
我如何使用 C# 来做到这一点?
您需要首先确保您的开发盒上安装了 SMO(SQL Server 管理对象)并可供您使用。如果您已在其上安装了某个版本的 SQL Server,则通常会出现这种情况。
如果您有可用的 SMO 库,您可以使用以下代码片段进行操作:
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......
}
为此,您需要有以下项目参考
和命名空间Microsoft.SqlServer.SmoExtended
在称为的程序集中实现Microsoft.SqlServer.SmoExtended.dll
应该在目录中找到C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
如果您安装了 SMO。
如果你没有安装SMO,你可以从here对于 SQL Server 2008 或here适用于 SQL Server 2008 R2(还有适用于 SQL Server 2005 的旧版本)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)