c# 备份数据库恢复数据库
/// <summary>
/// 对数据库的备份和恢复操作,Sql语句实现
/// </summary>
/// <param name="cmdText">实现备份或恢复的Sql语句</param>
/// <param name="isBak">该操作是否为备份操作,是为true否,为false</param>
private bool BakReductSql(string cmdText, bool isBak)
{
SqlCommand cmdBakRst = new SqlCommand();
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=master;uid=sa;pwd=zqnb_123;");
try
{
conn.Open();
cmdBakRst.Connection = conn;
cmdBakRst.CommandType = CommandType.Text;
if (!isBak) //如果是恢复操作
{
string set = "drop database [NbV3.1Db] ";
cmdBakRst.CommandText =set+ cmdText ;
}
else
{
cmdBakRst.CommandText = cmdText;
}
cmdBakRst.ExecuteNonQuery();
return true;
}
catch (SqlException sexc)
{
return false;
}
catch (Exception ex)
{
return false;
}
finally
{
cmdBakRst.Dispose();
conn.Close();
conn.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
string saveAway = @"d:\\1.bak";
string cmdText = @"backup database [NbV3.1Db] to disk='" + saveAway + "'";
BakReductSql(cmdText, true);
}
private void button2_Click(object sender, EventArgs e)
{
string openAway = @"d:\\1.bak";
string cmdText = @"restore database [NbV3.1Db] from disk='" + openAway + "'";
BakReductSql(cmdText, false);
}
----先删除所有的的数据库引用才能还原
string restoreSql = String.Format("ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE RESTORE DATABASE [{1}] FROM DISK = '{2}' WITH REPLACE", dbName, dbName, openAway);