一个被认为是更好的标准?一个比另一个快吗?或者,主要是偏好? GetOrdinal 很好,因为您可以自己调用列名,而不必担心在 SQL 中计算字段的索引,但我想知道使用其中一个是否比另一个有好处。
按索引阅读:
while (reader.Read())
{
Column1 = reader.GetValue(0).ToString().Trim();
Column2 = reader.GetValue(1).ToString().Trim();
}
Reader.GetOrdinal:
while (reader.Read())
{
data.Column1 = reader.GetValue(reader.GetOrdinal("COLUMN1")).ToString();
data.Column2 = reader.GetValue(reader.GetOrdinal("COLUMN2")).ToString();
data.Column3 = reader.GetDateTime(reader.GetOrdinal("COLUMN3"));
}
最佳答案
reader.GetOrdinal(string)将获得列序号,给定列名
我们可以从SqlDataReader看到GetOrdinal
源码它将从 _fieldNameLookup.GetOrdinal
返回一个索引(_fieldNameLookup
字段是一个 FieldNameLookup
类)
_fieldNames
is a hashtable stores the index, match via case-sensitive
override public int GetOrdinal(string name) {
SqlStatistics statistics = null;
try {
statistics = SqlStatistics.StartTimer(Statistics);
if (null == _fieldNameLookup) {
CheckMetaDataIsReady();
_fieldNameLookup = new FieldNameLookup(this, _defaultLCID);
}
return _fieldNameLookup.GetOrdinal(name); // MDAC 71470
}
finally {
SqlStatistics.StopTimer(statistics);
}
}
我们可以看到FieldNameLookup
类的GetOrdinal
方法的源码。
public int GetOrdinal(string fieldName) { // V1.2.3300
if (null == fieldName) {
throw ADP.ArgumentNull("fieldName");
}
int index = IndexOf(fieldName);
if (-1 == index) {
throw ADP.IndexOutOfRange(fieldName);
}
return index;
}
public int IndexOf(string fieldName) { // V1.2.3300
if (null == _fieldNameLookup) {
GenerateLookup();
}
int index;
object value = _fieldNameLookup[fieldName];
if (null != value) {
// via case sensitive search, first match with lowest ordinal matches
index = (int) value;
}
else {
// via case insensitive search, first match with lowest ordinal matches
index = LinearIndexOf(fieldName, CompareOptions.IgnoreCase);
if (-1 == index) {
// do the slow search now (kana, width insensitive comparison)
index = LinearIndexOf(fieldName, ADP.compareOptions);
}
}
return index;
}
Is one quicker than the other?
如果您已经知道列存在索引号 reader.GetValue(0)
将更快然后 reader.GetValue(reader.GetOrdinal("COLUMN1"))
因为它没有不会导致资源从 reader.GetOrdinal
方法获取列索引。
Is one considered better standard?
没有比较标准,因为reader.GetValue(0)
和reader.GetValue(reader.GetOrdinal("COLUMN1"))
做的是同一件事,和之前的回答一样。
reader.GetValue(reader.GetOrdinal("COLUMN1"))
比 reader.GetValue(0)
更好,因为列名更容易知道索引。
关于C# - 按索引的 SQLDataReader 与 SQLDataReader.GetOrdinal(ColumnName),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58956345/