本文介绍了System.IndexOutOfRangeException上SqlDataReader的值使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个返回三个整数一个SqlDataReader。然而,存在这样的情况,当两个整数的将返回空值。
要避开这个问题我写了以下内容:
INT shoppingCartHeadID = 0;
INT BILLID = 0;
INT delID = 0;conn.Open();
读者= comm.ExecuteReader();
如果(reader.Read())
{
shoppingCartHeadID = Convert.ToInt32(读卡器[shoppingCartHeadID]); 如果(!reader.IsDBNull(BILLID))
{
BILLID = Convert.ToInt32(读卡器[BILLID]);
} 如果(!reader.IsDBNull(delID))
{
delID = Convert.ToInt32(读卡器[delID]);
}
}
reader.Close();
不幸的是,我仍然得到错误信息。有什么建议?
PS我也试过这个没有运气
解决方案
I would try to access by index instead of column name, just in case you are passing a not existing column name.
Also, make sure you wrap your reader with a using block so in any case even if there is an exception your reader will be properly closed and disposed, for example in this way:
...
using(var reader = comm.ExecuteReader())
{
if (reader.Read())
{
shoppingCartHeadID = Convert.ToInt32(reader[0]);
if (!reader.IsDBNull(1))
{
billID = Convert.ToInt32(reader[1]);
}
if (!reader.IsDBNull(2))
{
delID = Convert.ToInt32(reader[2]);
}
}
}
这篇关于System.IndexOutOfRangeException上SqlDataReader的值使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!