标签:
1 private void btnBack_Click(object sender, EventArgs e) 2 { 3 string saveAway = @"C:\1.bak"; 4 // string cmdText = @"backup database " + System.Configuration.ConfigurationSettings.AppSettings["dbName"] + " to disk=‘" + saveAway + "‘"; 5 string cmdText = @"backup database TestDemo to disk=‘" + saveAway + "‘"; 6 BakReductSql(cmdText, true); 7 } 8 9 private void btnRestore_Click(object sender, EventArgs e) //恢复 10 { 11 // string openAway = this.tbxReductLoad.Text.ToString().Trim();//读取文件的路径 12 string openAway = @"c:\1.bak";//读取文件的路径 13 //string cmdText = @"restore database " + System.Configuration.ConfigurationSettings.AppSettings["dbName"] + " from disk=‘" + openAway + "‘"; 14 string cmdText = @"restore database TestDemo from disk=‘" + openAway + "‘ with REPLACE;"; 15 BakReductSql(cmdText, false); 16 } 17 /// <summary> 18 /// 对数据库的备份和恢复操作,Sql语句实现 19 /// </summary> 20 /// <param name="cmdText">实现备份或恢复的Sql语句</param> 21 /// <param name="isBak">该操作是否为备份操作,是为true否,为false</param> 22 private void BakReductSql(string cmdText, bool isBak) 23 { 24 SqlCommand cmdBakRst = new SqlCommand(); 25 SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=master;uid=sa;pwd=sa;"); 26 try 27 { 28 conn.Open(); 29 cmdBakRst.Connection = conn; 30 cmdBakRst.CommandType = CommandType.Text; 31 if (!isBak) //如果是恢复操作 32 { 33 string setOffline = "Alter database TestDemo Set Offline With rollback immediate ;"; 34 string setOnline = " Alter database TestDemo Set Online With Rollback immediate;"; 35 cmdBakRst.CommandText = setOffline + cmdText + setOnline; 36 } 37 else 38 { 39 cmdBakRst.CommandText = cmdText; 40 } 41 cmdBakRst.ExecuteNonQuery(); 42 if (!isBak) 43 { 44 MessageBox.Show("恭喜你,数据成功恢复为所选文档的状态!", "系统消息"); 45 } 46 else 47 { 48 MessageBox.Show("恭喜,你已经成功备份当前数据!", "系统消息"); 49 } 50 } 51 catch (SqlException sexc) 52 { 53 MessageBox.Show("失败,可能是对数据库操作失败,原因:" + sexc, "数据库错误消息"); 54 } 55 catch (Exception ex) 56 { 57 MessageBox.Show("对不起,操作失败,可能原因:" + ex, "系统消息"); 58 } 59 finally 60 { 61 cmdBakRst.Dispose(); 62 conn.Close(); 63 conn.Dispose(); 64 } 65 }
备份文件保存在数据库服务器上
标签:
原文地址:http://www.cnblogs.com/9527y/p/4398526.html