如何检查数据读取器中是否存在列 [英] How to check if a column exists in a datareader
本文介绍了如何检查数据读取器中是否存在列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在尝试读取数据列之前检查其是否存在列
我尝试下面的一些代码
I want to check if a column exists in the datareader before attempting to read it
i try some of code below
string ColumnValue;
if (dr["ColumnName"] != null)
ColumnValue = dr["ColumnName"].ToString();
if (dr.GetSchemaTable().Columns["ColumnName"] != null)
ColumnValue = dr["ColumnName"].ToString();
if (dr.GetSchemaTable().Columns.IndexOf("ColumnName")> 0)
ColumnValue = dr["ColumnName"].ToString();
但它不起作用.关于这个的任何想法.
谢谢
but its not work. any idea about this.
Thanks
推荐答案
循环将为您解决问题.
遍历所有列的名称,并检查您的列是否存在.
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://stackoverflow.com/questions/373230/check-for- column-name-in-a-sqldatareader-object [ ^ ]
Refer this thread
http://stackoverflow.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 theGetSchemaTable()
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".
这篇关于如何检查数据读取器中是否存在列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文