程序员的部落

导航

代码实现ASP.NET数据库的备份和还原

//数据库备份
     protected void btnBackup_Click(object sender, EventArgs e)
    {
        string bakname = "cc";
        string sql = "backup database tt to disk = '" + Server.MapPath("").ToString() + "\\"
        + bakname //备份文件名
        + ".bak'";

        SqlConnection scon = new SqlConnection("server=.;uid=sa;pwd=sa;database=tt");
        scon.Open();
        SqlCommand sc = new SqlCommand(sql, scon);
        sc.ExecuteNonQuery();

    }

//数据库的还原


    protected void Button1_Click(object sender, EventArgs e)
    {
        //string path = this.FileUpload1.PostedFile.FileName; //获得备份路径及数据库名称
        string path = "D:/1.BAK";
        //string dbname = this.DropDownList1.SelectedValue;
        string SqlStr1 = "Server=.;database=WebZone;Uid=sa;Pwd=sa";
        string SqlStr2 = "use master restore database WebZone from disk='" + path + "'";
        SqlConnection con = new SqlConnection(SqlStr1);
        con.Open();
        try
        {
            SqlCommand com = new SqlCommand(SqlStr2, con);
            com.ExecuteNonQuery();
            Response.Write("<script language=javascript>alert('还原数据成功!');</script>");
        }
        catch (Exception error)
        {
            Response.Write(error.Message);Response.Write("<script language=javascript>alert('还原数据失败!');</script>");
       
        }
        finally
        {
            con.Close();
        }
    }

posted on 2009-04-02 10:16  程序员的部落  阅读(237)  评论(0编辑  收藏  举报