日期:2014-05-16  浏览次数:20357 次

C# SQLSERVER2008数据库备份和还原的两种方法 (有进度条)

C# SQLSERVER2008数据库备份和还原的两种方法 (有进度条)

  1. :方法一(不使用SQLDMO):

  2. ?

  3. ///

  4. ///备份方法

  5. ///

  6. SqlConnectionconn=newSqlConnection("Server=.;Database=master;UserID=sa;Password=sa;");

  7. ?

  8. SqlCommandcmdBK=newSqlCommand();

  9. cmdBK.CommandType=CommandType.Text;

  10. cmdBK.Connection=conn;

  11. cmdBK.CommandText=@"backupdatabasetesttodisk='C:/ba'withinit";

  12. ?

  13. try

  14. {

  15. conn.Open();

  16. cmdBK.ExecuteNonQuery();

  17. MessageBox.Show("Backupsuccessed.");

  18. }

  19. catch(Exceptionex)

  20. {

  21. MessageBox.Show(ex.Message);

  22. }

  23. finally

  24. {

  25. conn.Close();

  26. conn.Dispose();

  27. }

  28. ?

  29. ?

  30. ///

  31. ///还原方法

  32. ///

  33. SqlConnectionconn=newSqlConnection("Server=.;Database=master;UserID=sa;Password=sa;Trusted_Connection=False");

  34. conn.Open();

  35. ?

  36. //KILLDataBaseProcess

  37. SqlCommandcmd=newSqlCommand("SELECTspidFROMsysprocesses,sysdatabasesWHEREsysprocesses.dbid=sysdatabases.dbidANDsysdatabases.Name='test'",conn);

  38. SqlDataReaderdr;

  39. dr=cmd.ExecuteReader();

  40. ArrayListlist=newArrayList();

  41. while(dr.Read())

  42. {

  43. list.Add(dr.GetInt16(0));

  44. }

  45. dr.Close();

  46. for(inti=0;i<list.Count;i++)

  47. {

  48. cmd=newSqlCommand(string.Format("KILL{0}",list),conn);

  49. cmd.ExecuteNonQuery();

  50. }

  51. ?

  52. SqlCommandcmdRT=newSqlCommand();

  53. cmdRT.CommandType=CommandType.Text;

  54. cmdRT.Connection=conn;

  55. cmdRT.CommandText=@"restoredatabasetestfromdisk='C:/ba'";

  56. ?

  57. try

  58. {

  59. cmdRT.ExecuteNonQuery();

  60. MessageBox.Show("Restoresuccessed.");

  61. }

  62. catch(Exceptionex)

  63. {

  64. MessageBox.Show(ex.Message);

  65. }

  66. finally

  67. {

  68. conn.Close();

  69. }

?

?

  1. 方法二(使用SQLDMO):

  2. ?

  3. ///

  4. ///备份方法

  5. ///

  6. SQLDMO.Backupbackup=newSQLDMO.BackupClass();

  7. SQLDMO.SQLServerserver=newSQLDMO.SQLServerClass();

  8. //显示进度条

  9. SQLDMO.BackupSink_PercentCompleteEventHandlerprogress=newSQLDMO.BackupSink_PercentCompleteEventHandler(Step);

  10. backup.PercentComplete+=progress;

  11. ?

  12. try

  13. {

  14. server.LoginSecure=false;

  15. server.Connect(".","sa","sa");

  16. backup.Action=SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;

  17. backup.Database="test";

  18. backup.Files=@"D:/test/myProg/backupTest";

  19. backup.BackupSetName="test";

  20. backup.BackupSetDescription="Backupthedatabaseoftest";

  21. backup.Initialize=true;

  22. backup.SQLBackup(server);

  23. MessageBox.Show("Backupsuccessed.");

  24. }

  25. catch(Exceptionex)

  26. <