我的本地数据库 Ships(HistID,ShipName,ShipLength)
中有一个表。我正在轮询数据库以查找所有具有 HistID == theme
的船舶,但从未输入 while(reader.Read()){}
。此外,我的 Ships 表不止一行(在另一个 SO 问题中看到了这个问题)所以我不确定为什么我不能将结果存储到元组列表中。在 Visual Studio 2015 中单独执行查询会产生正确的结果。
public List<Tuple<String, int>> getHistoricalShipList(int theme)
{
List<Tuple<String, int>> list = new List<Tuple<string, int>>();
using (db)
{
cmd = new SqlCommand(@"Select ShipName, ShipLength from Ships Where HistID=@theme", db);
cmd.Parameters.AddWithValue("@theme", theme);
db.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows) // always returning false
{
//Loop through results
while (reader.Read())
{
String shipName = reader[0].ToString();
int shipLength = Convert.ToInt32(reader[1]);
list.Add(Tuple.Create(shipName, shipLength));
}
}
db.Close();
}
return list;
}
EDIT::按照建议从查询中删除了单引号,但仍然有同样的问题。
最佳答案
您的 theme
是 int
类型,您将其用单引号括起来,就像它是一个字符串值一样。删除引号,但更重要的是,使用参数
cmd = new SqlCommand(string.Format(@"Select ShipName, ShipLength from Ships Where HistID={0}", theme), db);
切勿使用字符串连接/字符串格式来构建 SQL 语句,您的代码很容易出现 SQL injection .
cmd = new SqlCommand(@"Select ShipName, ShipLength from Ships Where HistID=@theme", db);
cmd.Parameters.AddWithValue("@theme", theme);
//Or more precise
//cmd.Parameters.Add(new SqlParameter("@theme", SqlDbType.Int) {Value = theme});
你没有得到任何行的原因是,你的字段 HistID
是数字类型,你试图将它与字符串值 进行比较(通过将值包含在单个引用)。
关于c# - SqlDataReader.Read() 在 C# 中始终为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631998/