Search code examples
c#postgresqldatareader

Get string from postgresql database with datareader


I was use this for add value for variable with MySQL :

var var1 = datareader.GetString("something");

But with PostgreSQL i get the following error:

"cannot convert from string to int"

How can I get string from PostgreSQL database?


Solution

  • You can get it with

    var var1 = datareader.GetString(reader.GetOrdinal("something"));
    

    Usually GetString wants an integer that represent the position of the column in the returned recordset. But any specific provider can extend GetString to get directly the value from the string value (as the provider for MySql does), but if they don't provide this extension you need to use the pattern that requires usage of GetOrdinal

    Of course you could write the extension yourself. Just add this method in a static class

    public static object GetString(this NpgsqlDataReader source, string colname)
    {
         if(string.IsNullOrEmpty(colname))
            throw ArgumentException("Need a column name");
    
         return source.GetString(source.GetOrdinal(colname));
    }
    

    and now, your way to call GetString will work.