c#、sql数据库备份还原
1.在项目中添加SQLDmo dll文件引用(SQLDMO(SQL Distributed Management Objects,SQL分布式管理对象))
2在相应页面加using SQLDMO引用
3.下面是用C#语言书写的用于Microsoft SQL Server数据库备份和恢复的类:
using System;
namespace DbService
{
/// <summary>
/// DbOper类,主要实现对Microsoft SQL Server数据库的备份和恢复
/// </summary>
public sealed class DbOper
{
/// <summary>
/// DbOper类的构造函数
/// </summary>
private DbOper()
{
}
/// <summary>
/// 数据库备份
/// </summary>
public static void DbBackup()
{
try
{
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
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;
}
}
/// <summary>
/// 数据库恢复
/// </summary>
public static void DbRestore()
{
try
{
SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
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;
}
}
}
}
参见在C#中运用SQLDMO备份和恢复Microsoft SQL Server数据库
http://dev.csdn.net/develop/article/28/28564.shtm
当不使用要恢复的数据库时以上方法可行,但当你使用了数据库时就必须杀死该进程
代码如下:
/// <summary>
/// 还原数据库函数
/// </summary>
/// <param name="strDbName">数据库名</param>
/// <param name="strFileName">数据库备份文件的完整路径名</param>
/// <returns></returns>
public bool RestoreDB(string strDbName,string strFileName)
{
//PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
//服务器名,数据库用户名,数据库用户名密码
svr.Connect("localhost","sa","hai") ;
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
//杀死使用strDbName数据库的进程
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
{
svr.KillProcess(lPID) ;
}
}
SQLDMO.Restore res = new SQLDMO.RestoreClass() ;
res.Action = 0 ;
res.Files = strFileName ;
res.Database = strDbName ;
res.ReplaceDatabase = true ;
res.SQLRestore(svr) ;
return true ;
}
catch
{
return false;
}
finally
{
svr.DisConnect() ;
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。