asp.net远程备份sql server2000数据库的方法

其实备份和恢复数据库都是利用SQL Server提供的SQL语句来备份的。
备份:use master;backup database @name to disk=@path;
恢复:use master;restore database @name from disk=@path;
上面用的是参数化SQL语句,可以在程序执行的时候动态给参数赋值。
代码:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DatabaseAction.aspx.cs" Inherits="DatabaseAction" %>

  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head runat="server">
  5.     <title>无标题页</title>
  6. </head>
  7. <body>
  8.     <form id="form1" runat="server">
  9.     <div>
  10.     <table border="0" width="100%">
  11.     <tr><td colspan="2">数据库还原和备份</td></tr>
  12.     <tr><td>请选择数据库</td><td>
  13.         <asp:DropDownList ID="ddlDatabaseList" runat="server">
  14.         </asp:DropDownList></td></tr>
  15.     <tr><td>
  16.          数据库文件名</td><td>
  17.         <asp:TextBox ID="txtDbFileName" runat="server"></asp:TextBox></td></tr>
  18.     <tr><td>
  19.          操作选项</td><td>
  20.         <asp:RadioButton ID="rbBackup" runat="server" Checked="True" GroupName="action" Text="备份" />
  21.         <asp:RadioButton ID="rbRestore" runat="server" GroupName="action" Text="还原" /></td></tr>
  22.         <tr><td>
  23.          操作</td><td>
  24.              <asp:Button ID="btnOK" runat="server" OnClick="btnOK_Click" Text="执行" /></td></tr>
  25.     </table>
  26.     </div>
  27.     </form>
  28. </body>
  29. </html>
后台代码:
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Collections;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. using System.Data.SqlClient;

  12. /// <summary>
  13. /// 功能说明:本例中演示在asp.net中如何备份和恢复数据库
  14. /// 备份数据库主要使用数据库的备份语句。数据库备份文件放在
  15. /// App_Data文件夹下。
  16. public partial class DatabaseAction : System.Web.UI.Page
  17. {
  18.     protected void Page_Load(object sender, EventArgs e)
  19.      {
  20.         if (!Page.IsPostBack)
  21.          {
  22.             //在DropDownList中绑定所有数据库
  23.              SqlConnection connection = new SqlConnection("Data Source=localhost;User ID=sa;Password=sa");
  24.              SqlCommand command = new SqlCommand("sp_helpdb", connection);
  25.              command.CommandType = CommandType.StoredProcedure;
  26.              connection.Open();
  27.              SqlDataReader reader = command.ExecuteReader();
  28.              ddlDatabaseList.DataSource = reader;
  29.              ddlDatabaseList.DataTextField = "Name";
  30.              ddlDatabaseList.DataBind();
  31.              reader.Close();
  32.              connection.Close();
  33.          }
  34.      }
  35.     protected void btnOK_Click(object sender, EventArgs e)
  36.      {
  37.         string dbFileName = txtDbFileName.Text.Trim();
  38.          SqlConnection connection = new SqlConnection("Data Source=localhost;User ID=sa;Password=sa");
  39.         string dbName = ddlDatabaseList.SelectedValue;
  40.         if (!dbFileName.EndsWith(".bak"))
  41.          {
  42.              dbFileName += ".bak";
  43.          }
  44.         if (rbBackup.Checked)//备份数据库
  45.          {
  46.              SqlCommand command = new SqlCommand("use master;backup database @name to disk=@path;",connection);
  47.              connection.Open();
  48.             string path=Server.MapPath("~\\App_Data")+"\\"+dbFileName;
  49.              command.Parameters.AddWithValue("@name", dbName);
  50.              command.Parameters.AddWithValue("@path", path);
  51.              command.ExecuteNonQuery();
  52.              connection.Close();
  53.          }
  54.         else//恢复数据库
  55.          {
  56.              SqlCommand command = new SqlCommand("use master;restore database @name from disk=@path;", connection);
  57.              connection.Open();
  58.             string path = Server.MapPath("~\\App_Data") + "\\" + dbFileName;
  59.              command.Parameters.AddWithValue("@name", dbName);
  60.              command.Parameters.AddWithValue("@path", path);
  61.              command.ExecuteNonQuery();
  62.              connection.Close();
  63.          }
  64.      }
  65. }
   public void TransportFile()//将备份的文件传送到本机
    {
        System.IO.Stream iStream = null;
        //以10K为单位缓存:
        byte[] buffer = new Byte[10000];
        int length;
        long dataToRead;
        // 制定文件路径.
        string datestr = System.DateTime.Now.Date.ToString("yyyyMMdd");//系统当前日期YYYY-MM-DD
        //string formatdatestr = datestr.Substring(0,4) + datestr.Substring(5,2) + datestr.Substring(8,2);
        string filepath = @"E:\study\DMS\File\"+datestr+"";
        //  得到文件名.
        string filename = System.IO.Path.GetFileName(filepath);
        try
        {
            // 打开文件.
            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,System.IO.FileAccess.Read, System.IO.FileShare.Read);

            // 得到文件大小:
            dataToRead = iStream.Length;
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename+"BAK");
            while (dataToRead > 0)
            {
                //保证客户端连接
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, 10000);
                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();
                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    //结束循环
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            // 出错.
            throw ex;
        }
        finally
        {
            if (iStream != null)
            {
                //关闭文件
                iStream.Close();
            }
        }
    }

 

你可能感兴趣的:(数据库,职场,休闲)