DataReader best-practices

后端 未结 2 2038
轮回少年
轮回少年 2020-12-09 12:35

Similar to this question, but the answers never really got around to what I want to know. Is there any standards around getting values from a DataReader? I.e., is this

2条回答
  •  清歌不尽
    2020-12-09 13:08

    Here is the way that I do it:

    Int32 ordinal = dataReader.GetOrdinal("ColumnName");
    
    if (!dataReader.IsDBNull(ordinal))
        yourString = dataReader.GetString(ordinal);
    

    It is important to check for DBNull like I have shown above because if the field is null in the DataReader it will throw an exception when you try to retrieve it.

提交回复
热议问题