#region 数据库备份 BackupData
/// <summary>
/// 数据库备份
/// </summary>
/// <param name="dir">MapPath转换过的备份文件目录</param>
/// <param name="dbname">数据库名称</param>
/// <returns>返回string值为空表示备份成功</returns>
public static string BackupData(string dir, string dbname)
{
string ErrorString = "";
string bakpath = string.Format("{0}/bak{1}.bak", dir, Utility.timestring);///完整的路径
string strSql2 = string.Format("backup database {0} to disk='{1}'", dbname, bakpath);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(strSql2, conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception er)
{
ErrorString = er.Message;
}
}
}
return ErrorString;
}
#endregion
#region 还原数据库(还原数据库要有权限才能还原成功)RestoreData
/// <summary>
/// 还原数据库(还原数据库要有权限才能还原成功)
/// </summary>
/// <param name="bakpath">MapPath转换过的备份文件路径</param>
/// <param name="dbname">数据库名称</param>
/// <returns>返回string值为空表示还原成功</returns>
public static string RestoreData(string bakpath, string dbname)
{
string ErrorString = "";
///这里改成数据库管理员帐号和密码
//"Data Source=PKM-PC\\SQL05;Initial Catalog=dbtest;User Id=**;Pwd=****";
string cmdtxt = string.Format("use master restore database {0} from disk='{1}'", dbname, bakpath);
using (SqlConnection Conn = new SqlConnection(connectionString))
{
try
{
using (SqlCommand cmd = new SqlCommand(cmdtxt, Conn))
{
Conn.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception er)
{
ErrorString = er.Message;
}
}
return ErrorString;
}
#endregion