sqldmo(sql distributed management objects,sql分布式管理对象)封装了microsoft sql server数据库中的对象。sqldmo是microsoft sql server中企业管理器所使用的应用程序接口,所以它可以执行很多功能,其中当然也包括对数据库的备份和恢复。
当然要用到 sqldmo 来做这个工作
找到 sqldmo.dll这个文件
c:/program files/microsoft sql server/80/tools/binn/sqldmo.dll
用.net框架提供的工具转成受托管代码
tlbimp sqldmo.dll /out: c:/sqldmo.dll
sqldmo由microsoft sql server自带的sqldmo.dll提供,由于sqldmo.dll是一个com对象,所以大家在用之前必须在.net项目中添加对它的引用。
下面是用c#语言书写的用于microsoft sql server数据库备份和恢复的类:
using system;
namespace dbservice
{
/// <summary>
/// dboper类,主要应用sqldmo实现对microsoft sql server数据库的备份和恢复
/// </summary>
public sealed class dboper
{
/// <summary>
/// dboper类的构造函数
/// </summary>
private dboper()
{
}
/// <summary>
/// 数据库备份
/// </summary>
public static void dbbackup()
{
sqldmo.backup obackup = new sqldmo.backupclass();
sqldmo.sqlserver osqlserver = new sqldmo.sqlserverclass();
try
{
osqlserver.loginsecure = false;
osqlserver.connect("localhost", "sa", "1234");
obackup.action = sqldmo.sqldmo_backup_type.sqldmobackup_database;
obackup.database = "northwind";
obackup.files = @"d:/northwind.bak";
obackup.backupsetname = "northwind";
obackup.backupsetdescription = "数据库备份";
obackup.initialize = true;
obackup.sqlbackup(osqlserver);
}
catch
{
throw;
}
finally
{
osqlserver.disconnect();
}
}
/// <summary>
/// 数据库恢复
/// </summary>
public static void dbrestore()
{
sqldmo.restore orestore = new sqldmo.restoreclass();
sqldmo.sqlserver osqlserver = new sqldmo.sqlserverclass();
try
{
osqlserver.loginsecure = false;
osqlserver.connect("localhost", "sa", "1234");
orestore.action = sqldmo.sqldmo_restore_type.sqldmorestore_database;
orestore.database = "northwind";
orestore.files = @"d:/northwind.bak";
orestore.filenumber = 1;
orestore.replacedatabase = true;
orestore.sqlrestore(osqlserver);
}
catch
{
throw;
}
finally
{
osqlserver.disconnect();
}
}
}
}
新闻热点
疑难解答