这是我的代码:
db.Open();
string updateString = "SELECT TOP 1 RTRIM(kol) kol, RTRIM(adres) adres, RTRIM(numwave) numwave FROM sorters WHERE kodprod=@kodprod AND sorter_kod=@sorter AND moved_ok IS NULL ORDER BY CAST(kol as int)";
try
{
SqlCommand command = new SqlCommand(updateString, db);
//command.Parameters.AddWithValue("@numdoc", NumDoc);
command.Parameters.AddWithValue("@kodprod", KodProd.Id);
command.Parameters.AddWithValue("@sorter", SorterKod);
SqlDataReader reader = command.ExecuteReader();
reader.Read();//here error
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
reader.Close();
}
catch (Exception ex)
{ }
运行代码时为什么会出现此错误?:
无数据存在时读取无效
答案 0 :(得分:5)
您可以检查DataReader是否已准备好提取行
if(reader.HasRows)
{
//do the coding here
}
答案 1 :(得分:1)
我相信错误实际上会发生在下一行,即当您通过索引[]
运算符访问阅读器时。您需要做的是在访问之前检查reader.Read()
的结果:
if (reader.Read())
{
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
}
由于您只返回最多一行(TOP 1
),因此将为零行或一行。
答案 2 :(得分:0)
您应该while loop
检查阅读器是否包含数据。如果您确定查询只返回一行,也可以使用IF
。如果有多行,则应使用While
。在您的情况下,IF
也可以完成这项工作,因为您只需要TOP1
string updateString = "SELECT TOP 1 RTRIM(kol) kol, RTRIM(adres) adres,
RTRIM(numwave) numwave FROM sorters WHERE
kodprod=@kodprod AND sorter_kod=@sorter
AND moved_ok IS NULL ORDER BY CAST(kol as int)";
try
{
SqlCommand command = new SqlCommand(updateString, db);
//command.Parameters.AddWithValue("@numdoc", NumDoc);
command.Parameters.AddWithValue("@kodprod", KodProd.Id);
command.Parameters.AddWithValue("@sorter", SorterKod);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
}
reader.Close();
}
答案 3 :(得分:0)
使用reader.HasRows
string updateString = "SELECT TOP 1 RTRIM(kol) kol, RTRIM(adres) adres, RTRIM(numwave) numwave FROM sorters WHERE kodprod=@kodprod AND sorter_kod=@sorter AND moved_ok IS NULL ORDER BY CAST(kol as int)";
try
{
SqlCommand command = new SqlCommand(updateString, db);
//command.Parameters.AddWithValue("@numdoc", NumDoc);
command.Parameters.AddWithValue("@kodprod", KodProd.Id);
command.Parameters.AddWithValue("@sorter", SorterKod); SqlDataReader
reader = command.ExecuteReader();
if(reader.HasRows)
while(reader.Read())//here error
{
Kol = reader["kol"].ToString();
Adres = reader["adres"].ToString();
NumWave = reader["numwave"].ToString();
NumDoc = reader["numdoc"].ToString();
}
reader.Close();
}
catch{}
编辑:抱歉格式错误,从Android应用程序发布代码是一团糟。
编辑:请参阅Microsoft示例here