How to GetDecimal from database by ColumnName (NOT: by column number) ?

  • Thread starter Thread starter Mark Poppers
  • Start date Start date
M

Mark Poppers

Normally I retrieve an (e.g. DECIMAL) value from a database record by enumerating
the column number like:

Decimal localvar = reader.GetDecimal(3);

Which means "Get the decimal value from the 3rd column in the database record".

However is there a way to tell CSharp to retrieve the Decimal value from
the column named "MYAMOUNT" ?

I could imagine that it works similar to:

Decimal localvar = reader.GetDecimal(GetColumnNumberFor("MYAMOUNT"));

Marl
 
Have you looked at the GetOrdinal method of the DataReader?
Example:
SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader();

int idPos = productsSqlDataReader.GetOrdinal("ID");
int firstNamePos = productsSqlDataReader.GetOrdinal("LastName");
int lastNamePos = productsSqlDataReader.GetOrdinal("FirstName");

while (productsSqlDataReader.Read())
{
Console.WriteLine("ID = " + productsSqlDataReader[idPos]);
Console.WriteLine("FirstName = " + productsSqlDataReader[firstNamePos]);
Console.WriteLine("LastName = " + productsSqlDataReader[lastNamePos]);
}

Peter
 
Which means "Get the decimal value from the 3rd column in the
database record".

Actually it means get the value from the column with index 3, which is
(by convention) the 4th column.

For t'other, try GetOrdinal("MYAMOUNT") to get the index first, either
separately or inline. It is easy enough to throw this into a wrapper
method if it helps.

inline example: decimal localvar =
reader.GetDecimal(reader.GetOrdinal("MYAMOUNT"));

Marc
 
Mark said:
Normally I retrieve an (e.g. DECIMAL) value from a database record by enumerating
the column number like:

Decimal localvar = reader.GetDecimal(3);

Which means "Get the decimal value from the 3rd column in the database record".

However is there a way to tell CSharp to retrieve the Decimal value from
the column named "MYAMOUNT" ?

I could imagine that it works similar to:

Decimal localvar = reader.GetDecimal(GetColumnNumberFor("MYAMOUNT"));

Other has already suggested GetOrdinal, but you could also use:

decimal localvar = (decimal)reader["MYAMOUNT"];

Arne
 
Back
Top