// 备份按钮
protected void BtnBack_Click(object sender, EventArgs e)
{
string saveAway = "D:\\S2.bak";//备份文件保存位置
string cmdText = @"use master;backup database TrainSearch to disk='" + saveAway + "'";//TrainSearch数据库名称,你要改为你自己的
SqlCommand cmd = new SqlCommand();
cmd.CommandText = cmdText;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
Common.ShowMessage.Show(Page, "yes", "备份成功!");
con.Close();
BackUpTime bt = new BackUpTime();
string time = DateTime.Now.ToString();
if (bt.EditBackTime(1, time))
{
}
else
{
}
}
//还原按钮
protected void BtnHf_Click(object sender, EventArgs e)
{
string strsql_kill = "SELECT spid FROM sys.sysprocesses ,sys.sysdatabases WHERE sys.sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='TrainSearch'";
DataSet ds = new DataSet();
SqlCommand cmdd = new SqlCommand();
cmdd.Connection = con;
cmdd.CommandText = strsql_kill;
con.Open();
cmdd.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter(cmdd);
sda.Fill(ds);
ArrayList list = new ArrayList();
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
list.Add(ds.Tables[0].Rows[j][0].ToString());
}
for (int i = 0; i < list.Count; i++)
{
cmdd = new SqlCommand("KILL " + list[i].ToString(), con);
cmdd.ExecuteNonQuery();
}
con.Close();
string cmdText = @"use master;restore database TrainSearch from disk='D:\S2.bak' with REPLACE";//D:\S2.bak本分数据库源
SqlCommand cmd = new SqlCommand();
cmd.CommandText = cmdText;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
Common.ShowMessage.Show(Page, "yes", "还原成功!");
con.Close();
}
当然备份和还原数据库你都可以自己选择路径,我这里了方便就没加那个功能,想实现可以加一个FIleUpload控件用于浏览数据源或者备份路径