(Backup Database SQL Server in Asp.net) – Để Backup Database SQL Server, người quản trị thường vào SQL Server Management Studio để thực hiện. Tuy nhiên với những phần mềm hoặc Website phải thuê các gói Hosting của nhà cung cấp khác thì  việc truy cập vào SQL Server Management Studio rất khó khăn. Do nhiều nhà cung cấp Hosting không mở cổng SQL để truy cập từ xa. Vậy có cách nào để có thể Backup Database SQL trên ngay phần mềm không?  Bài viết dưới đây sẽ hướng dẫn các bạn cách xây dựng chức năng Backup Data từ ngay trên giao diện phần mềm.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




B1: Mở file Default.aspxdưới dạng HTML và  nhập mã HTML

<%@ PageTitle="How to Back up SQL Server Database Using ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="BackupDatabaseSQL._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table cellpadding="3"cellspacing="5"border="0"width="60%">
        <tr>
            <td>
                <divclass="panel panel-default">
                    <divclass="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="BACKUP DATA"></asp:label>
                    </div>
                    <divclass="panel-body">
                        <table cellspacing="2"cellpadding="3"border="0"width="100%">
                            <tr>
                                <td style="width:25%;" valign="top">
                                    <asp:Label ID="plFileName"runat="server"resourcekey="plFileName"Text="Database Name"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtDatabaseName"CssClass="form-control"Width="180px"runat="server"></asp:TextBox>
                                    <asp:Label ID="Label2" runat="server"ForeColor="#CCCCCC"Text="(example pub.bak)"></asp:Label>
                                     <asp:RequiredFieldValidatorID="valDatabaseName"ValidationGroup="validate"CssClass="NormalRed"runat="server"ErrorMessage="Enter Database Name" ControlToValidate="txtDatabaseName"></asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <asp:label id="lblMessage"runat="server"></asp:label><br />
                                </td>
                            </tr>
                        </table>
                    </div>
                    <divclass="modal-footer">
                        <div class="btn-group">
                            <asp:LinkButton id="cmdBackup"runat="server"CssClass="btn btn-small" ValidationGroup="validate" Text="Backup" Causesvalidation="true">
                            </asp:LinkButton>
                        </div>
                    </div>
                </div>
            </td>
        </tr>       
    </table>
</asp:Content>

B2: Viết Code cho file Default.aspx

'Visit http://thuthuatlaptrinh.blogspot.com for more ASP.NET Tutorials
Imports System.Data.SqlClient
Imports System.IO

Namespace BackupDatabaseSQL

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private builder As New SqlConnectionStringBuilder()
        Private database As String = ""

#End Region

#Region "Private Method"

        Private SubCreateFolder()
            Dim FilePath As String = MapPath("~/Backup")
            If Not Directory.Exists(FilePath) Then
                ' if not, create it.
                Directory.CreateDirectory(FilePath)
            End If
        End Sub

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Page.IsPostBack = False Then

                    CreateFolder()

                    Dim colConnections As ConnectionStringSettingsCollection= ConfigurationManager.ConnectionStrings
                    Dim CurrentDate AsDate = Now.Date
                    Dim sDate AsString = IIf(Day(CurrentDate) > 9, Day(CurrentDate), "0" & Day(CurrentDate))
                    sDate &= IIf(Day(CurrentDate) > 9, Month(CurrentDate), "0" & Month(CurrentDate))
                    sDate &= Year(CurrentDate)
                    sDate = sDate.Replace("/", "")

                    For EachobjConnection As ConnectionStringSettingsIn colConnections
                        If objConnection.Name.ToLower <> "localmysqlserver"And objConnection.Name.ToLower <> "localsqlserver" Then
                            builder.ConnectionString = objConnection.ConnectionString
                            database = builder.InitialCatalog
                            txtDatabaseName.Text = database & "_"& sDate
                        End If
                    Next
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private SubcmdBackup_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdBackup.Click
            Dim Backup_Path As String = MapPath("~/Backup")
            Dim builder As New SqlConnectionStringBuilder()
            Dim colConnections AsConnectionStringSettingsCollection = ConfigurationManager.ConnectionStrings

            Dim sDatabaseName As String = txtDatabaseName.Text.Trim

            If Directory.Exists(Backup_Path) Then
                For EachobjConnection As ConnectionStringSettingsIn colConnections
                    If objConnection.Name.ToLower <> "localmysqlserver" And objConnection.Name.ToLower <> "localsqlserver" Then
                        builder.ConnectionString = objConnection.ConnectionString
                        database = builder.InitialCatalog
                        Dim myCnn As SqlConnection = NewSqlConnection(builder.ConnectionString)
                        myCnn.Open()
                        Dim cmd As SqlCommand = New SqlCommand()
                        Dim sql As String = "BACKUP DATABASE "& database & " TO DISK = N'"& Backup_Path & "\\" & sDatabaseName & ".bak' WITH INIT"
                        cmd.Connection = myCnn
                        cmd.CommandText = sql
                        Try
                            cmd.ExecuteNonQuery()
                        Catch ex As Exception
                            lblMessage.Text = ex.Message
                            lblMessage.ForeColor = System.Drawing.Color.Red
                        Finally
                            myCnn.Close()
                            lblMessage.Text = "Backup Database Sucessfully"
                            lblMessage.ForeColor = System.Drawing.Color.Green
                        End Try
                    End If
                Next
            End If
        End Sub

#End Region
       
    End Class

End Namespace

- B3: Chạy Project, phần mềm sẽ tự động lấy tên Database đang kết nối & ngày tháng năm hiện tại. Sau khi kích nút Backup chương trình sẽ tự động Backup Database SQL và file sẽ được lưu trữ tại thư mục Backup của Project.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Chúc các bạn thành công!

Quang Bình

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top