asp.net 備份和恢複數據庫

来源:http://www.cnblogs.com/shouce/archive/2016/01/06/5104315.html
-Advertisement-
Play Games

前臺: ...


前臺:

複製代碼
<form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="備份資料庫" OnClick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
        <asp:GridView ID="gv_DataBasefile" runat="server" AutoGenerateColumns="False" Width="100%"
            OnRowCommand="gv_DataBasefile_RowCommand">
            <RowStyle HorizontalAlign="center" />
            <Columns>
                <asp:TemplateField HeaderText="文件名">
                    <ItemTemplate>
                        <%#Eval("Name") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="創建時間">
                    <ItemTemplate>
                        <%# objIdtu.GetDateTime( Eval("CreationTime"),"yyyy-MM-dd HH:mm:ss")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="修改時間">
                    <ItemTemplate>
                        <%# objIdtu.GetDateTime(Eval("LastWriteTime"), "yyyy-MM-dd HH:mm:ss")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="路徑">
                    <ItemTemplate>
                        <%# Eval("DirectoryName")%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="還原">
                    <ItemTemplate>
                        <%--CommandArgument 傳遞兩個數據  Name,DirectoryName--%>
                        <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="../images/x1root.gif"
                            CommandArgument='<%# Eval("Name")+","+Eval("DirectoryName")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
複製代碼

後臺:

 

複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HanSoft.BusinessLogic;
using Insus.NET;
using CAF.DBUtility;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using HanSoft.SQLServerDAL;

public partial class information_backDB : System.Web.UI.Page
{

    protected InsusDateTimeUtility objIdtu = new InsusDateTimeUtility();

    InsusIOUtility objIotu = new InsusIOUtility();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Data_Binding();
        }
    }

    private void Data_Binding()
    {
        DirectoryInfo dInfo = new DirectoryInfo(Server.MapPath("~/backSql"));

        this.gv_DataBasefile.DataSource = dInfo.GetFiles();

        this.gv_DataBasefile.DataBind();
    }


    /// <summary>
    /// 備份資料庫
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            BACKUP();
            Label1.Text = "資料庫備份成功!";
            Data_Binding();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }

    /// <summary>
    /// 備份資料庫方法
    /// </summary>
    private void BACKUP()
    {
        string DBname = "1220";

        string backUpDBname = DBname + "_" + objIdtu.GetDateTimeMillisecond();//這一步是資料庫名+年月日+隨機數

        objIotu.MakeDirectory(Server.MapPath("~/backSql"));  //這一步是在根目錄下麵生成一個文件夾,名叫 backsql

        string str_sql = " BACKUP DATABASE [" + DBname + "] TO DISK = '" + Server.MapPath("~/").ToString() + "backSql\\" + backUpDBname + ".bak'";

        int i = SqlHelper.ExecuteNonQuery(str_sql);
    }

    /// <summary>
    /// 還原資料庫
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gv_DataBasefile_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        SelectObjectIndexBLL SoIndexBLL = new SelectObjectIndexBLL();

        SqlConnection connection = new SqlConnection("Data Source=192.168.1.98;User ID=sa;Password=123");

        string path_name = e.CommandArgument.ToString();

        string[] array = { };

        string[] array1 = { };

        array = path_name.Split(',');

        string dbFileName = array[1].ToString();

        array1 = array[0].ToString().Split('_');

        string dbName = array1[0].ToString();

        SqlCommand command = new SqlCommand("use master;restore database @name from disk=@path WITH REPLACE;", connection);

        string path = dbFileName + "//" + array[0];  //全路徑

        command.Parameters.AddWithValue("@name", dbName);  //dbName還原目標資料庫名

        command.Parameters.AddWithValue("@path", path);

        DataTable dt_spid = SoIndexBLL.GetDataList(" select spid from master..sysprocesses where dbid=db_id('1220') ").Tables[0];


        if (dt_spid.Rows.Count > 0)
        {
            for (int i = 0; i < dt_spid.Rows.Count; i++)
            {
                string sql = " kill " + Convert.ToString(dt_spid.Rows[i]["spid"]) + " ";

                //SqlDataAdapter sqldap = new SqlDataAdapter(sql, connection);//--------------1

                SqlCommand commd = new SqlCommand(sql, connection);//----------2

                connection.Open();

                commd.ExecuteReader();//-------------2

                connection.Close();

               
            } Label2.Text = " 資料庫恢覆成功! ";
        }

        connection.Open();

        command.ExecuteNonQuery();//-----------------1

        connection.Close();
        




    }
}
複製代碼

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Sample.ashx(handler): using System;using System.Collections.Generic;using System.Web;using System.IO;public ...
  • 為什麼要對資料庫進行設計? 當我們要存儲的數據比較少的是後當然不需要對資料庫進行設計,但是當我們對數據的需求量越來越大時對資料庫的設計就很有必要性了!如果資料庫的設計不當會造成數據冗餘、修改複雜、操作數據異常等問題而好的資料庫設計則可以減少不必要的數據冗餘,通過合理的數據規劃提高系統的性能! 什麼是...
  • 在實際的項目開發中我們可能經常要修改已有的代碼,可能我們經常說開閉原則對已有的代碼不准修改,但是實際上很難,那麼下麵的3種方法也許能幫助我們改善對代碼的修改。1:新生方法有時候在我們開發的時候需要像系統加入新的功能時候這個時候我們就可能改變我們原有方法的結構。那麼下麵有一個簡單例子以前添加用戶的.....
  • 1、創建webapi項目,提供介面方法如下:/// /// 獲取租戶、位置下的所有感測器 /// /// [AcceptVerbs("POST")] [Route("api/Sensors/GetSensors")] ...
  • publicstaticvoidDebugFunctionTree(stringmessage){try{System.Diagnostics.StackTracest=newSystem.Diagnostics.StackTrace();System.Diagnostics.StackFrame....
  • 目 錄第十三章 中英文版本切換設計... 213.1 不用自帶的資源文件的理由... 213.2 配置文件... 213.3 語言管理類... 313.4 應用管理類... 1213.5 小結... 12第十三章 中英文版本切換設計13.1 不用自帶的資源文件的理由 可以利用resx資源文件進行多語...
  • json序列化和反序列化幫助類:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.Serialization;using System.Runt...
  • // /// 遞歸獲取文件夾目錄下文件 /// /// 需要遞歸遍歷的文件夾 /// 遍歷規則『委托』 public static void LoopFolder(string pathName, Action fileRul...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...