萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> C# 對數據庫的備份和恢復操作,Sql語句實現

C# 對數據庫的備份和恢復操作,Sql語句實現

   ///

 

  /// 對數據庫的備份和恢復操作,Sql語句實現

  ///

 

  /// 實現備份或恢復的Sql語句

  /// 該操作是否為備份操作,是為true否,為false

  private void BakReductSql(string cmdText,bool isBak,string dbname)

  {

  string conString=DataBase.dbConnection.sqlNoDBNameConnect();

  SqlConnection conn3 = new SqlConnection(conString);

  SqlCommand cmdBakRst = new SqlCommand();

  try

  {

  if(conn3.State==ConnectionState.Closed)

  conn3.Open();

  cmdBakRst.Connection = conn3;

  cmdBakRst.CommandType = CommandType.Text;

  if (!isBak) //如果是恢復操作

  {

  string setOffline = "Alter database "+dbname+" Set Offline With rollback immediate ";

  string setOnline = " Alter database " + dbname + " Set Online With Rollback immediate";

  cmdBakRst.CommandText = setOffline + cmdText + setOnline ;

  }

  else

  {

  cmdBakRst.CommandText = cmdText;

  }

  cmdBakRst.ExecuteNonQuery();

  if (!isBak)

  {

  MessageBox.Show("數據成功恢復為所選文檔的狀態!", "系統消息");

  }

  else

  {

  MessageBox.Show("恭喜,你已經成功備份當前數據!", "系統消息");

  }

  }

  catch (SqlException sexc)

  {

  MessageBox.Show("失敗,可能是對數據庫操作失敗,原因:" + sexc, "數據庫錯誤消息");

  }

  catch (Exception ex)

  {

  MessageBox.Show("對不起,操作失敗,可能原因:" + ex, "系統消息");

  }

  finally

  {

  cmdBakRst.Dispose();

  conn3.Close();

  }

  }

copyright © 萬盛學電腦網 all rights reserved