c# 备份与还原SQL/ACCESS 数据库的代码
本文导语: c#备份与还原sql server与access的代码。 代码示例: //使用前须先引用SQLDMO.dll ADOX.dll JRO.dll 等组件,无须独立安装 //如:C:Program FilesCommon FilesSystemadomsadox.dll //如:C:Program FilesCommon FilesSystemadomsjro.dll //如:C:Program FilesMicrosoft SQL Ser...
c#备份与还原sql server与access的代码。
//使用前须先引用SQLDMO.dll ADOX.dll JRO.dll 等组件,无须独立安装
//如:C:Program FilesCommon FilesSystemadomsadox.dll
//如:C:Program FilesCommon FilesSystemadomsjro.dll
//如:C:Program FilesMicrosoft SQL Server80ToolsBinnSQLDMO.DLL
using System;
using System.IO;
///
/// 数据库恢复和备份
///
public class DataBak
{
public DataBak()
{
//
// TO
//DO: 在此处添加构造函数逻辑
//
}
#region SQL数据库备份
///
/// SQL数据库备份
///
/// SQL服务器IP或(Localhost)
/// 数据库登录名
/// 数据库登录密码
/// 数据库名
/// 备份到的路径
public static bool BakSql(string ServerIP, string LoginName, string LoginPass, string DBName, string BackPath)
{
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect(ServerIP, LoginName, LoginPass);
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = DBName;
oBackup.Files = BackPath;
oBackup.BackupSetName = DBName;
oBackup.BackupSetDescription = "数据库备份";
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
return true;
}
catch (Exception e)
{
return false;
throw new Exception(e.ToString());
}
finally
{
oSQLServer.DisConnect();
}
}
#endregion
#region SQL恢复数据库
///
/// SQL恢复数据库
///
/// SQL服务器IP或(Localhost)
/// 数据库登录名
/// 数据库登录密码
/// 要还原的数据库名
// 数据库备份的路径
public static bool RecoverSql(string ServerIP, string LoginName, string LoginPass, string DBName, string BackPath)
{
SQLDMO.Restore orestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
//杀死所有SQL进程
SQLDMO.QueryResults qr = oSQLServer.EnumProcesses(-1);
int iColPIDNum = -1;
int iColDbName = -1;
for (int i = 1; i