我这里有两个函数。改成你的数据连接字符串,传入要备份的数据库名和远程绝对路径。
#region 备份选定的SQLServer数据库
/// <summary>
/// 备份SQLServer选定的数据库
/// </summary>
/// <param name="dbName">原数据库名</param>
/// <param name="filePathName">备份文件名</param>
/// <returns></returns>
public static string SqlBackup(string dbName, string filePathName)
{
string SqlStr1 = "Data Source=...;Initial Catalog='..';Persist Security Info=True;User ID=Uid;Password=Pwd";
string SqlStr2 = "backup database " + dbName + " to disk='" + filePathName + ".bak'";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
try
{
if (File.Exists(filePathName))
{
msg = "此文件已存在,请从新输入!";
return msg;
}
SqlCommand com = new SqlCommand(SqlStr2, con);
com.ExecuteNonQuery();
msg = "备份数据成功!";
return msg;
}
catch (Exception error)
{
msg = "备份数据失败!" + error.Message;
return msg;
}
finally
{
con.Close();
}
}
#endregion
#region 恢复SQLServer数据库
/// <summary>
/// 恢复SQLServer数据库
/// </summary>
/// <param name="dbName">原数据库名</param>
/// <param name="filePathName">要还原的文件</param>
/// <returns></returns>
public static string SqlRevert(string dbName, string filePathName)
{
string SqlStr1 = "Data Source=...;Initial Catalog='..';Persist Security
Info=True;User ID=Uid;Password=Pwd";
string SqlStr2 = "use master restore database " + dbName + " from disk='" + filePathName + "'";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
try
{
SqlCommand com = new SqlCommand(SqlStr2, con);
com.ExecuteNonQuery();
msg = "还原数据成功!";
return msg;
}
catch (Exception error)
{
msg = "还原数据失败!" + error.Message;
return msg;
}
finally
{
con.Close();
}
}
#endregion