sql sever2005数据库备份和还原(Asp.net C#)

// 备份按钮
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控件用于浏览数据源或者备份路径


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值