ASP.NET中备份和恢复数据库

1.备份和恢复SQL数据库
  <script language="C#" runat="server">
  
   // 注意本节的数据库连接字符串
   string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer1"];
   
   void Page_Load(object sender, System.EventArgs e)
   {
    if(!IsPostBack)
    {
     // 创建连接及执行数据库操作
     string db_query = "sp_helpdb";

     SqlCommand myCommand = new SqlCommand(db_query, new SqlConnection(ConnStr));
     myCommand.Connection.Open();
     SqlDataReader dr = myCommand.ExecuteReader();

     // 将数据库列表绑定到下拉列表控件(DropDownList)
     dbDropDownList.DataSource = dr;
     dbDropDownList.DataTextField = "name";
     dbDropDownList.DataBind();

     //关闭DataReader对象和数据库连接
     dr.Close();
     myCommand.Connection.Close();
    }
   }
   
   void dbDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
   {
    txtPath.Text = @"C:/BACKUP/" + dbDropDownList.SelectedValue + ".bak";
   }
   
   void btnBackup_Click(object sender, System.EventArgs e)
   {
    string path = txtPath.Text;
    string dbname = dbDropDownList.SelectedValue;

    string backupSql = "use master;";
    backupSql += "backup database @dbname to disk = @path;";
   
    SqlCommand myCommand = new SqlCommand(backupSql, new SqlConnection(ConnStr));

    myCommand.Parameters.Add("@dbname", SqlDbType.Char);
    myCommand.Parameters["@dbname"].Value = dbname;
    myCommand.Parameters.Add("@path", SqlDbType.Char);
    myCommand.Parameters["@path"].Value = path;

    try
    {
     myCommand.Connection.Open();
     myCommand.ExecuteNonQuery();
     lblMsg.Text = "备份成功";
    }
    catch(Exception ex)
    {
     lblMsg.Text = "备份失败<br>" + ex.ToString();
    }
    finally
    {
     myCommand.Connection.Close();
    }
   }
   
   void btnRestore_Click(object sender, System.EventArgs e)
   {
    string path = pathTextBox.Text;
    string dbname = dbDropDownList.SelectedValue;

    string restoreSql = "use master;";
    restoreSql += "restore database @dbname from disk = @path;";

    SqlCommand myCommand = new SqlCommand(restoreSql, new SqlConnection(ConnStr));

    myCommand.Parameters.Add("@dbname", SqlDbType.Char);
    myCommand.Parameters["@dbname"].Value = dbname;
    myCommand.Parameters.Add("@path", SqlDbType.Char);
    myCommand.Parameters["@path"].Value = path;

    try
    {
     myCommand.Connection.Open();
     myCommand.ExecuteNonQuery();
     lblMsg.Text = "恢复成功";
    }
    catch(Exception ex)
    {
     lblMsg.Text = "恢复失败<br>" + ex.ToString();
    }
    finally
    {
     myCommand.Connection.Close();
    }
   }
  
  </script>

2.添加一个dropdownlist控件,两个Button按钮,一个TextBox文本框

阅读更多
想对作者说点什么? 我来说一句

ASP.NET备份恢复数据库

2009年07月01日 37KB 下载

没有更多推荐了,返回首页

不良信息举报

ASP.NET中备份和恢复数据库

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭