DataReader.GetString() via columnname

后端 未结 1 1042
孤城傲影
孤城傲影 2020-12-06 17:41
Dictionary Fields = new Dictionary();
for (int i = 0; i < reader.FieldCount; i++)
{
     Fields.Add(reader.GetName(i), i);
}

this._MyField1 = reader.GetString(Fields[         


        
相关标签:
1条回答
  • 2020-12-06 18:15

    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));
        }
    }
    // ...
    
    0 讨论(0)
提交回复
热议问题