用asp.net代码怎样实现数据库备份和还原
用asp.net代码怎样实现数据库备份和还原,这个我现在已经实现了,代码是网上找的,代码如下:/// <summary>
/// 还原数据库函数
/// </summary>
/// <param name="strDbName">数据库名</param>
/// <param name="strFileName">数据库备份文件的完整路径名</param>
/// <returns></returns>
public bool RestoreDB(string strDbName,string strFileName)
{
//PBar = pgbMain ;
SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass() ;
try
{
//服务器名,数据库用户名,数据库用户名密码
svr.Connect("localhost","sa","hai") ;
SQLDMO.QueryResults qr = svr.EnumProcesses(-1) ;
int iColPIDNum = -1 ;
int iColDbName = -1 ;
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
//杀死使用strDbName数据库的进程
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName) ;
if (strDBName.ToUpper() == strDbName.ToUpper())
{
svr.KillProcess(lPID) ;
}
}
SQLDMO.Restore res = new SQLDMO.RestoreClass() ;
res.Action = 0 ;
res.Files = strFileName ;
res.Database = strDbName ;
res.ReplaceDatabase = true ;
res.SQLRestore(svr) ;
return true ;
}
catch
{
return false;
}
finally
{
svr.DisConnect() ;
}
}
这是数据库还原的代码,当还原数据库成功后,我再想在这张页面上进行对数据库的操作时就会出错,错误信息如下:
在向服务器发送请求时发生传输级错误。 (provider: 共享内存提供程序, error: 0 - 管道的另一端上无任何进程。)
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.Data.SqlClient.SqlException: 在向服务器发送请求时发生传输级错误。 (provider: 共享内存提供程序, error: 0 - 管道的另一端上无任何进程。)
我自己认为可能是在还原数据库的时候把和这个数据库有关的进程都杀死了,而现在再要对数据库进行操作时,发生了这个错误,
问有没有人知道怎样解决这个问题啊,很急啊 --------------------编程问答-------------------- 用这个呢]
http://news.softhouse.com.cn/news/show/691.html --------------------编程问答-------------------- 其體不了解﹐應該是進程殺死了﹐數據庫還沒有啟動 --------------------编程问答-------------------- using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
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();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string SqlStr1 = "Server=(local);database='" + this.DropDownList1.SelectedValue + "';Uid=sa;Pwd=";
string SqlStr2 = "backup database " + this.DropDownList1.SelectedValue + " 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='Main.aspx'</script>");
return;
}
SqlCommand com = new SqlCommand(SqlStr2, con);
com.ExecuteNonQuery();
Response.Write("<script language=javascript>alert('备份数据成功!');location='Main.aspx'</script>");
}
catch (Exception)
{
Response.Write("<script language=javascript>alert('备份数据失败!')</script>");
}
finally
{
con.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string path = this.File1.PostedFile.FileName; //获得备份路径及数据库名称
string dbname = this.DropDownList1.SelectedValue;
string SqlStr1 = "Server=(local);database='" + this.DropDownList1.SelectedValue + "';Uid=sa;Pwd=";
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('还原数据成功!');location='Main.aspx'</script>");
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write("<script language=javascript>alert('还原数据失败!')</script>");
}
finally
{
con.Close();
}
}
} --------------------编程问答--------------------
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 System.Web.UI.HtmlControls;
using Microsoft;
using Microsoft.SqlServer;
using System.Data.SqlClient;
using System.Collections;
//using SQLDMO;
/// <summary>
/// Summary description for DatabaseManage
/// </summary>
public class DatabaseManage
{
string ConnString = string.Empty;
public DatabaseManage(string strConnString)
{
ConnString = strConnString;
}
public string BACKUPDatabase()
{
SqlParameter part1 = new SqlParameter("@Name", "MyNwind_yy");
SqlParameter part2 = new SqlParameter("@Adress", "d:\\MyNwind_yy.dat");
SqlParameter[] parts ={ part1, part2 };
string ret = string.Empty;
try
{
SqlHelper.ExecuteNonQuery(ConnString, CommandType.StoredProcedure, "BACKUPDatabase", parts);
ret = "备份成功!";
}
catch (Exception ex)
{
ret = "备份失败!" + ex;
}
return ret;
}
public string BACKUPDatabaseX()
{
SqlParameter part1 = new SqlParameter("@Name", "MyNwind_yy");
SqlParameter part2 = new SqlParameter("@Adress", "d:\\MyNwind_yy.dat");
SqlParameter part3 = new SqlParameter("@try", 1);
SqlParameter[] parts ={ part1, part2, part3 };
string ret = string.Empty;
try
{
SqlHelper.ExecuteNonQuery(ConnString, CommandType.StoredProcedure, "BACKUPDatabase", parts);
ret = "备份成功!";
}
catch (Exception ex)
{
ret = "备份失败!" + ex;
}
return ret;
}
public string RESTOREDatabase()
{
//SqlParameter part1 = new SqlParameter("@Name", "MyNwind_yy");
//SqlParameter[] parts ={ part1};
//string ret = string.Empty;
//try
//{
// SqlHelper.ExecuteNonQuery(ConnString, CommandType.StoredProcedure, "RESTOREDatabase", parts);
// ret = "还原成功!";
//}
//catch(Exception ex)
// {
// ret = "还原失败!" + ex;
// }
// return ret;
string ret = string.Empty;
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=True");
conn.Open();
//KILL DataBase Process
SqlCommand cmd = new SqlCommand("SELECT spid FROM sysprocesses ,sysdatabases WHERE
sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='myCrm'", conn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
ArrayList list = new ArrayList();
try
{
while (dr.Read())
{
list.Add(dr.GetInt16(0));
}
dr.Close();
for (int i = 0; i < list.Count; i++)
{
cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
cmd.ExecuteNonQuery();
}
SqlCommand cmdRT = new SqlCommand();
SqlCommand cmmf = new SqlCommand("execute sp_detach_db 'myCrm'", conn);
cmdRT.CommandType = CommandType.Text;
cmdRT.Connection = conn;
cmdRT.CommandText = @"restore database test from disk='d:\\MyNwind_yy.dat', MOVE 'MyNwind_yy' TO 'D:\\myCrm.mdf'
";
cmdRT.ExecuteNonQuery();
ret = "还原成功!";
}
catch
{
ret = "还原失败!";
}
finally
{
conn.Close();
}
return ret;
}
--------------------编程问答-------------------- 里面用的是sqlhelp.cs类 微软的 --------------------编程问答-------------------- 在asp.net中备份还原SQL Server数据库
在web中,安全性主要体现在两个方面:一个是程序安全性,即防止网页在插入恶意代码;另一个是数据库安全性,这个我们可以经常备份数据库来实现。在文中,我将演示如果在网页中备份和恢复数据库。其实备份和恢复数据库都是利用SQL Server提供的SQL语句来备份的。备份:use master;backup database @name to disk=@path;恢复:use master;restore database @name from disk=@path;上面用的是参数化SQL语句,可以在程序执行的时候动态给参数赋值。 --------------------编程问答--------------------
--------------------编程问答-------------------- 古老的问题
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/// <summary>
/// 功能说明:本例中演示在asp.net中如何备份和恢复数据库
/// 备份数据库主要使用数据库的备份语句。数据库备份文件放在
/// App_Data文件夹下。
/// 作者:周公
/// 日期:2008-08-19
/// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/19/2796077.aspx
/// </summary>
public partial class DatabaseAction : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//在DropDownList中绑定所有数据库
SqlConnection connection = new SqlConnection("Data Source=ZHOUFOXCN;User ID=sa;Password=sa");
SqlCommand command = new SqlCommand("sp_helpdb", connection);
command.CommandType = CommandType.StoredProcedure;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
ddlDatabaseList.DataSource = reader;
ddlDatabaseList.DataTextField = "Name";
ddlDatabaseList.DataBind();
reader.Close();
connection.Close();
}
}
protected void btnOK_Click(object sender, EventArgs e)
{
string dbFileName = txtDbFileName.Text.Trim();
SqlConnection connection = new SqlConnection("Data Source=ZHOUFOXCN;User ID=sa;Password=sa");
string dbName = ddlDatabaseList.SelectedValue;
if (!dbFileName.EndsWith(".bak"))
{
dbFileName += ".bak";
}
if (rbBackup.Checked)//备份数据库
{
SqlCommand command = new SqlCommand("use master;backup database @name to disk=@path;",connection);
connection.Open();
string path=Server.MapPath("~\\App_Data")+"\\"+dbFileName;
command.Parameters.AddWithValue("@name", dbName);
command.Parameters.AddWithValue("@path", path);
command.ExecuteNonQuery();
connection.Close();
}
else//恢复数据库
{
SqlCommand command = new SqlCommand("use master;restore database @name from disk=@path;", connection);
connection.Open();
string path = Server.MapPath("~\\App_Data") + "\\" + dbFileName;
command.Parameters.AddWithValue("@name", dbName);
command.Parameters.AddWithValue("@path", path);
command.ExecuteNonQuery();
connection.Close();
}
}
}
补充:.NET技术 , ASP.NET