25 April 2013

Extension - Adding a parameter to an ODBC command; the easy way

I find that adding parameters to an OdbcCommand is not very straightforward. That's why I wrote myself an extension to make it easier:
public static void AddParameter(this OdbcCommand command, string name, OdbcType type, object value, bool isNull = false) {
  if (command != null && name.HasValue()) { //"HasValue()" is another extension which simply returns ''!IsNullOrEmpty''. 
    if (!name.StartsWith("@"))
      name = '@' + name;
    if (value == null || isNull)
      value = DBNull.Value;
    command.Parameters.Add(new OdbcParameter(name, type));
    command.Parameters[name].Value = value;
  }
}
It takes care of the '@', replaces NULL by DBNull and adds the parameter in two steps as it is supposed to. It has a parameter isNull, in which you can say things like "if the int value = 0 then it constitutes NULL".