ASP.NET 恢複備份Sqlserver實現代碼

來源:互聯網
上載者:User

最近做的一個項目因為伺服器是在特殊機房上的,因為安全方面的考慮,不能給我們開發人員提供FTP服務,所以每次更新版本都得自己跑一趟,而他的機房有很遠,所以我一直想能不能開發一個維護版本的系統呢,對資料庫和代碼進行線上更新,就不用自己跑了,於是就有了下面的嘗試,線上恢複和備份SQL Server:

前台代碼: 複製代碼 代碼如下:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SqlDbMgmt.aspx.cs" Inherits="SysSourceMgmt.SqlDbMgmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="width: 100px">
<span style="font-size: 9pt">操 作 數 據 庫</span>
</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server" Font-Size="9pt" Width="124px">
</asp:DropDownList>
<asp:TextBox ID="txtDbName" runat="server"></asp:TextBox>
</td>
<td style="width: 100px">
</td>
</tr>
<tr>
<td style="width: 100px">
<span style="font-size: 9pt">備份名稱和位置</span>
</td>
<td style="width: 100px">
<asp:TextBox ID="TextBox1" runat="server" Font-Size="9pt" Width="117px"></asp:TextBox>
</td>
<td style="width: 100px">
<span style="font-size: 9pt; color: #ff3300">(如D:\beifen)</span>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="Button1" runat="server" Font-Size="9pt" OnClick="Button1_Click" Text="備份資料庫" />
</td>
</tr>
</table>
</div>
<div style="width: 100%; height: 100px">
<table>
<tr>
<td style="width: 100px; height: 21px">
<span style="font-size: 9pt">操 作 數 據 庫</span>
</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server" Font-Size="9pt" Width="124px">
</asp:DropDownList>
</td>
<td style="width: 100px; height: 21px">
</td>
</tr>
<tr>
<td style="width: 100px">
<span style="font-size: 9pt">操 作 數 據 庫</span>
</td>
<td style="width: 100px">
<asp:FileUpload ID="FileUpload1" runat="server" Font-Size="9pt" Width="190px" />
</td>
<td style="width: 100px">
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="Button2" runat="server" Font-Size="9pt" OnClick="Button2_Click" Text="還原資料庫" />
<asp:Button ID="Button3" runat="server" Font-Size="9pt" OnClick="Button3_Click" Text="強制還原資料庫" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

後台: 複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Diagnostics;
namespace SysSourceMgmt
{
public partial class SqlDbMgmt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
string SqlStr1 = "Server=(local);DataBase=master;Uid=sa;Pwd=";
string SqlStr2 = "Exec sp_helpdb";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
SqlCommand com = new SqlCommand(SqlStr2, con);
SqlDataReader dr = com.ExecuteReader();
this.DropDownList1.DataSource = dr;
this.DropDownList1.DataTextField = "name";
this.DropDownList1.DataBind();
dr.Close();
con.Close();
SqlStr1 = "Server=(local);DataBase=master;Uid=sa;Pwd=";
SqlStr2 = "Exec sp_helpdb";
con = new SqlConnection(SqlStr1);
con.Open();
com = new SqlCommand(SqlStr2, con);
dr = com.ExecuteReader();
this.DropDownList1.DataSource = dr;
this.DropDownList1.DataTextField = "name";
this.DropDownList1.DataBind();
dr.Close();
con.Close();
}
catch (Exception)
{
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string dbName = string.Empty;
if (DropDownList1.Items.Count != 0)
{
dbName = DropDownList1.SelectedValue.Trim();
}
else
{
dbName = txtDbName.Text.Trim();
}
string SqlStr1 = "Data Source=.\\sqlexpress;Initial Catalog='" + dbName + "';Integrated Security=True";
string SqlStr2 = "backup database " + dbName + " to disk='" + this.TextBox1.Text.Trim() + ".bak'";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
try
{
if (File.Exists(this.TextBox1.Text.Trim()))
{
Response.Write("<script language=javascript>alert('此檔案已存在,請從新輸入!');location='Default.aspx'</script>");
return;
}
SqlCommand com = new SqlCommand(SqlStr2, con);
com.ExecuteNonQuery();
Response.Write("<script language=javascript>alert('備份資料成功!');'</script>");
}
catch (Exception error)
{
Response.Write(error.Message);
Response.Write("<script language=javascript>alert('備份資料失敗!')</script>");
}
finally
{
con.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string path = this.FileUpload1.PostedFile.FileName; //獲得備份路徑及資料庫名稱
string dbName = string.Empty;
if (DropDownList1.Items.Count != 0)
{
dbName = DropDownList1.SelectedValue.Trim();
}
else
{
dbName = txtDbName.Text.Trim();
}
string SqlStr1 = "Data Source=.\\sqlexpress;Initial Catalog='" + dbName + "';Integrated Security=True";
string SqlStr2 = @"use master restore database " + dbName + " from disk='" + path + "'";
SqlConnection con = new SqlConnection(SqlStr1);
con.Open();
try
{
SqlCommand com = new SqlCommand(SqlStr2, con);
com.ExecuteNonQuery();
Response.Write("<script language=javascript>alert('還原資料成功!');'</script>");
}
catch (Exception error)
{
Response.Write(error.Message);
Response.Write("<script language=javascript>alert('還原資料失敗!')</script>");
txtDbName.Text = SqlStr2;
}
finally
{
con.Close();
}
}
/// <summary>
/// 恢複資料庫,可選擇是否可以強制還原(即在其他人在用的時候,依然可以還原)
/// </summary>
/// <param name="databasename">待還原的資料庫名稱</param>
/// <param name="databasefile">帶還原的備份檔案的完全路徑</param>
/// <param name="errormessage">恢複資料庫失敗的資訊</param>
/// <param name="forceRestore">是否強制還原(恢複),如果為TRUE,則exec killspid '資料庫名' 結束此資料庫的進程,這樣才能還原資料庫</param>
/// <returns></returns>
public bool RestoreDataBase(string databasename, string databasefile, ref string returnMessage, bool forceRestore, SqlConnection conn)
{
bool success = true;
string path = databasefile;
string dbname = databasename;
string restoreSql = "use master;";
if (forceRestore)//如果強制回複
restoreSql += string.Format("use master exec killspid '{0}';", databasename);
restoreSql += "restore database @dbname from disk = @path;";
SqlCommand myCommand = new SqlCommand(restoreSql, conn);
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
Response.Write(restoreSql);
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
returnMessage = "還原成功";
}
catch (Exception ex)
{
returnMessage = ex.Message;
success = false;
}
finally
{
myCommand.Connection.Close();
}
return success;
}
protected void Button3_Click(object sender, EventArgs e)
{
string path = this.FileUpload1.PostedFile.FileName; //獲得備份路徑及資料庫名稱
string dbName = string.Empty;
if (DropDownList1.Items.Count != 0)
{
dbName = DropDownList1.SelectedValue.Trim();
}
else
{
dbName = txtDbName.Text.Trim();
}
string returnMessage = string.Empty;
string SqlStr1 = "Data Source=.\\sqlexpress;Initial Catalog='" + dbName + "';Integrated Security=True";
SqlConnection con = new SqlConnection(SqlStr1);
RestoreDataBase(txtDbName.Text, path, ref returnMessage, true,con);
Response.Write(returnMessage);
}
}
}

經過實驗,大體完成了我需要的功能,具體最佳化後期進行中。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.