关闭

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

标签: asp.netstringpath数据库exceptionobject
740人阅读 评论(0) 收藏 举报

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文本框

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:30815次
    • 积分:429
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:10篇
    • 译文:0篇
    • 评论:2条
    文章分类
    文章存档