ASP.NET 恢复备份Sqlserver实现代码_实用技巧

最近做的一个项目因为服务器是在特殊机房上的,因为安全方面的考虑,不能给我们开发者提供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);
}
}
}

效果图:

 

经过试验,大体完成了我需要的功能,具体优化后期进行中。

时间: 2024-09-20 13:46:11

ASP.NET 恢复备份Sqlserver实现代码_实用技巧的相关文章

asp.net导出EXCEL的功能代码_实用技巧

复制代码 代码如下: //由gridviw导出为Excel public static void ToExcel(System.Web.UI.Control ctl) { HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls"); HttpContext.Current.Response.Charset = "UTF-8

asp.net 操作excel的实现代码_实用技巧

Excel是Microsoft公司的Office套件中的一种软件,他主要用来处理电子表格.Excel以界面友好.处理数据迅速等优点获得广大办公人员的欢迎.所以很多文档就以Excel的形式保存了下来.对于程序设计人员,在程序设计中,我们往往要访问Excel文件来获得数据.但由于Excel文件不是标准数据库,所以用程序语言来访问他就比较困难.  ASP.NET是Microsoft公司极力推荐的一个产品,作为.NET FrameWork框架中的一个重要组成部分,他主要用于Web设计.全新的设计理念.强

asp.net配置会话状态Session实现代码_实用技巧

下面来详细说明: 复制代码 代码如下: <sessionState timeout="timeout in minutes" cookieless="[true|false]" mode="Off|InProc|StateServer|SQLServer" stateConnectionString="tcpip=server:port" stateNetworkTimeout="for network ope

Asp.net 连接MySQL的实现代码[]_实用技巧

Mysql的connector/net5.0下载地址: http://dev.mysql.com/get/Downloads/Connector-Net/mysql-connector-net-5.0.6.zip/from/pick 安装好以后, 点属性,然后点查找目标,点向上一层目录,找到Binaries\.NET 2.0,然后将这个文件复制到你的工程目录下,一般这样的DLL文件会保存到bin目录下. 在代码页里输入using Mysql.Data.MysqlClient;然后再在Page_L

asp.net 通用的连接数据库实例代码_实用技巧

View Code 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <center><h2><font face="宋体">访问数据库的通用代码实例</font></h2>

asp.net保存远程图片的代码_实用技巧

注意:并没有实现CSS中的图片采集,且图片的正则还有待完善. 复制代码 代码如下: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using

asp.net 身份验证机制实例代码_实用技巧

ASP.NET提供了3种认证方式:windows身份验证.Forms验证和Passport验证. windows身份验证: IIS根据应用程序的设置执行身份验证.要使用这种验证方式,在IIS中必须禁用匿名访问. Forms验证:用Cookie来保存用户凭证,并将 未经身份验证的用户重定向到自定义的登录页. Passport验证:通过Microsoft的集中身份验证服务执行的,他为成员站点提供单独登录和核心配置文件服务. 关于这三种验证方式的配置,推荐一篇文章:http://www.jb51.ne

ASP.NET书籍信息录入实现代码_实用技巧

1. 在数据库中建立一个test数据库,在test数据库中建立一个book_info表.        Book_name      varchar(100)         Author               varchar(50)          Press               varchar(50)        Press_date      varchar(20)          Image              varchar(30) 2. 制作一个如下页面:

jsp和asp.net共享session值示例代码_实用技巧

思路是ASP.NET中序列化Session以二进制数据保存到数据库,然后由JSP读取数据库中的二进制数据反序列化成Session对象,再强制转化成的Session对象,在JAVA端转换时,出现了错误,找遍网上的资料也没能解决,故采用一种替换的方式. 替换的方式的思路: 登录的ASPX文件中,在登录成功后将Session中的变量值保存到数据库中的一张表,关键字使用ASP.NET的Session对象的SessionID,然后建立一个ASPX文件,取得当前登录用户的SessionID,并使用的ASP.