对数据库的备份和恢复操作,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();
  }
  }

你可能感兴趣的:(C#)