您好,欢迎访问一九零五行业门户网

调用sql语句实现SqlServer的备份和还原

调用sql语句实现sqlserver的备份还原,包括完整备份和差异备份,因为执行备份还原需要一定的时间,因此需要设定 commandtimeout参数。 /// summary /// 备份数据库 调用sql语句 /// /summary /// param name=strfilename备份文件名/param /// param name=back
调用sql语句实现sqlserver的备份还原,包括完整备份和差异备份,因为执行备份还原需要一定的时间,因此需要设定 commandtimeout参数。
///
/// 备份数据库 调用sql语句
///
/// 备份文件名
/// 0表示完整备份,为1表示差异备份
///
public bool backupdb(string strfilename, int backuptype)
{
//如果是差异备份,就是看一下文件是否存在,如果不存在,,就不执行
if (backuptype == 1 && file.exists(strfilename) == false)
{
return false;
}
bool result = false;
try
{
string[] strconnsqlarr = strconnsql.split(';');
string dbname = strconnsqlarr[4].tostring()。split('=')[1].tostring();//数据库名称
string backup_full = string.format(backup database {0} to disk = '{1}' ;, dbname, strfilename);
string backup_diff = string.format(backup database {0} to disk='{1}' with differential ;, dbname, strfilename);
wkk.dbutility.dbhelpersql.executesql(backuptype == 0 ? backup_full : backup_diff, 600);
result = true;
}
catch (exception ex)
{
common.log.writelog(string.format(备份{0}数据库失败, backuptype == 0 ? 完整 : 差异), ex);
//  system.diagnostics.debug.writeline(string.format(备份{0}数据库失败, backuptype == 0 ? 完整 : 差异));
result = false;
}
finally
{
if (result == true)
{
string str_infocontent = string.format(备份{0}数据库成功, backuptype == 0 ? 完整 : 差异);
// system.diagnostics.debug.writeline(str_infocontent);
}
}
return result;
}
///
/// 还原数据库 使用sql语句
///
/// 数据库名
/// 备份文件名
public bool restoredb(string strdbname, string strfilename)
{
bool result = false;
try
{
string strconnsql = configurationsettings.appsettings[connectionstring].tostring();
string[] strconnsqlarr = strconnsql.split(';');
string dbname = strconnsqlarr[4].tostring()。split('=')[1].tostring();//数据库名称
#region 关闭所有访问数据库的进程,否则会导致数据库还原失败 闫二永  17:39 2014/3/19
string cmdtext = string.format(exec sp_killthread @dbname='{0}', dbname);
wkk.dbutility.dbhelpersql.connectionstring = strconnsql.replace(dbname, master);
wkk.dbutility.dbhelpersql.executesql(cmdtext);
#endregion
string restore = string.format(restore database {0} from disk='{1}'with replace, dbname, strfilename);
wkk.dbutility.dbhelpersql.executesql(restore, 600);
result = true;
}
catch (exception ex)
{
messagebox.show(还原数据库失败rn + ex.message, 系统提示!, messageboxbuttons.ok, messageboxicon.warning);
common.log.writelog(string.format(还原数据库失败--{0}, datetime.now.tostring()), ex);
result = false;
}
finally
{
//恢复成功后需要重启程序
if (result)
{
//
}
}
return result;
}
///
///  执行一条sql语句
///
/// sql语句
/// 等待连接打开的时间(以秒为单位)。 默认值为 15 秒。
///
public static int executesql(string sqlstring, int settimeout)
{
using (sqlconnection connection = new sqlconnection(connectionstring))
{
using (sqlcommand cmd = new sqlcommand(sqlstring, connection))
{
try
{
connection.open();
cmd.commandtimeout = settimeout;
int rows = cmd.executenonquery();
connection.close();
return rows;
}
catch (system.data.sqlclient.sqlexception e)
{
connection.close();
throw e;
}
}
}
}
其它类似信息

推荐信息