且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查数据读取器中是否存在列

更新时间:2023-11-29 19:20:46

循环将为您解决问题.
遍历所有列的名称,并检查您的列是否存在.

looping will give u a solution of problem.
loop through the all columns name and check if your column is exist or not.

for (int i=0; i < dr.FieldCount; i++)
 {
            
         if (dr.GetName(i).Equals(columnName,StringComparison.InvariantCultureIgnoreCase))
          return true;
 }
return false; 


引用该线程

http://***.com/questions/373230/check-for- column-name-in-a-sqldatareader-object [ ^ ]
Refer this thread

http://***.com/questions/373230/check-for-column-name-in-a-sqldatareader-object[^]


我坚持使用GetSchemaTable()方法,如MSDN文档所述:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getschematable.aspx [ ^ ]

样本中可能有一两个错字:

I''d stick with the GetSchemaTable() method as the MSDN documentation explains:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getschematable.aspx[^]

maybe there''s a typo or two in your sample:

string ColumnName;

if (dr[ColumnName] != null)
      ColumnName = dr[ColumnName].ToString();

if (dr.GetSchemaTable().Columns[ColumnName] != null)
      ColumnName = dr[ColumnName].ToString();

if (dr.GetSchemaTable().Columns.IndexOf(ColumnName)> 0)
      ColumnName = dr[ColumnName].ToString();



尝试删除ColumnName周围的引号,以便您使用的是ColumnName的值,而不是文字"ColumnName".



try removing the quotes around ColumnName so you''re using the value of ColumnName and not the literal "ColumnName".