1. using System;
2. using System.Data;
3. using System.Configuration;
4. using System.Collections;
5. using System.Web;
6. using System.Web.Security;
7. using System.Web.UI;
8. using System.Web.UI.WebControls;
9. using System.Web.UI.WebControls.WebParts;
10. using System.Web.UI.HtmlControls;
11. using System.Data.SqlClient;
12.
13. /// <summary>
14. /// 功能说明:本例中演示在asp.net中如何备份和恢复数据库
15. /// 备份数据库主要使用数据库的备份语句。数据库备份文件放在
16. /// App_Data文件夹下。
17. /// 作者:周公
18. /// 日期:2008-08-19
19. /// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/19/2796077.aspx
20. /// </summary>
21.
public partial
class DatabaseAction : System.Web.UI.Page
22. {
void Page_Load() void Page_Load(object sender, EventArgs e)
24. {
25.
if (!Page.IsPostBack)
26. {
27. //在DropDownList中绑定所有数据库
28. SqlConnection connection =
new SqlConnection(
"Data Source=ZHOUFOXCN;User ID=sa;Password=sa");
29. SqlCommand command =
new SqlCommand(
"sp_helpdb", connection);
30. command.CommandType = CommandType.StoredProcedure;
31. connection.Open();
32. SqlDataReader reader = command.ExecuteReader();
33. ddlDatabaseList.DataSource = reader;
34. ddlDatabaseList.DataTextField =
"Name";
35. ddlDatabaseList.DataBind();
36. reader.Close();
37. connection.Close();
38. }
39. }
void btnOK_Click() void btnOK_Click(object sender, EventArgs e)
41. {
42.
string dbFileName = txtDbFileName.Text.
Trim();
43. SqlConnection connection =
new SqlConnection(
"Data Source=ZHOUFOXCN;User ID=sa;Password=sa");
44.
string dbName = ddlDatabaseList.SelectedValue;
45.
if (!dbFileName.EndsWith(
".bak"))
46. {
47. dbFileName +=
".bak";
48. }
49.
if (rbBackup.Checked)//备份数据库
50. {
51. SqlCommand command =
new SqlCommand(
"use master;backup database @name to disk=@path;",connection);
52. connection.Open();
53.
string path=Server.MapPath(
"~\\App_Data")+"\\"+dbFileName;
54. command.Parameters.AddWithValue(
"@name", dbName);
55. command.Parameters.AddWithValue(
"@path", path);
56. command.ExecuteNonQuery();
57. connection.Close();
58. }
59.
else//恢复数据库
60. {
61. SqlCommand command =
new SqlCommand(
"use master;restore database @name from disk=@path;", connection);
62. connection.Open();
63.
string path = Server.MapPath(
"~\\App_Data") + "\\" + dbFileName;
64. command.Parameters.AddWithValue(
"@name", dbName);
65. command.Parameters.AddWithValue(
"@path", path);
66. command.ExecuteNonQuery();
67. connection.Close();
68. }
69. }
70. }