C# SQL DELETE RETURN ONLY TRUE

Look: this fragment is useless:

  catch(SqlException sqlerro)
  {
    throw sqlerro; // exception catched and thrown unmodified
  }

If you want to return false when query fails:

  catch(SqlException sqlerro) {
    return false;
  }

In case you want to return false if no records are changed:

  return cmd.ExecuteNonQuery() > 0;

Finally, do not forget using, arrowhead antipattern, readability etc.

public bool Delete(int RGP) {
  // Argument/State validation
  if (objCon == null)
    return false; // No connection

  // SQL should be readable
  vsql = @"delete 
             from Pescador 
            where Rgp like @RGP";

  try {
    // Dispose IDisposable (via using)
    using (SqlCommand cmd = new SqlCommand(vsql, objCon)) {
      cmd.Parameters.AddWithValue("@RGP", RGP);
      //TODO: be sure that SET NOCOUNT is not ON 
      return cmd.ExecuteNonQuery() > 0;
    }
  }
  finally {
    Desconectar();
  }
}

Browse More Popular Posts

Leave a Comment