DataReader.GetString() via columnname

喜夏-厌秋 提交于 2020-03-09 04:58:25

问题


Dictionary Fields = new Dictionary();
for (int i = 0; i < reader.FieldCount; i++)
{
     Fields.Add(reader.GetName(i), i);
}

this._MyField1 = reader.GetString(Fields["field1"]);
this._Myfield2 = reader.GetInt16(Fields["field2"]);

doing this makes me want to cry but i can't seem to figure out how to use the type specfic retrieval methods by column name other than this way. please tell me there is a better way. this is specificly for DB2 but i would like the solution to work for MS Sql also if possible


回答1:


You're looking for the GetOrdinal method:

this._MyField1 = reader.GetString(dr.GetOrdinal("field1"));
this._Myfield2 = reader.GetInt16(dr.GetOrdinal("field2"));

I generally cache the ordinals in an anonymous type for performance and readability:

// ...
using (IDataReader dr = cmd.ExecuteReader())
{
    var ordinals = new {
                           Foo = dr.GetOrdinal("Foo"),
                           Bar = dr.GetOrdinal("Bar")
                       };

    while (dr.Read())
    {
        DoSomething(dr.GetString(ordinals.Foo), dr.GetInt16(ordinals.Bar));
    }
}
// ...


来源:https://stackoverflow.com/questions/3228972/datareader-getstring-via-columnname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!