c# - SqlDataReader.Read() 在 C# 中始终为 false

标签 c# sql

我的本​​地数据库 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::按照建议从查询中删除了单引号,但仍然有同样的问题。

最佳答案

您的 themeint 类型,您将其用单引号括起来,就像它是一个字符串值一样。删除引号,但更重要的是,使用参数

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/

相关文章:

php - 排行榜 - MySQL 按个人总和排序

c# - AutoMapper C# 运行时映射取决于对象属性

c# - MVC 使用 Html.CheckBoxFor 和可为空的 Bool

sql - 如何替换oracle中varchar2列中的重音字母

sql - ASP.Net MVC 数据格式化

sql - 分组依据在我的声明中不起作用。为什么

c# - Linq Entity Framework

c# - 如何使用 Watin 关闭浏览器 (IE8)?

c# - 为什么这里不使用LINQ ToList?

c# - 从 ASP.NET 中的 SQL Server 下载一个 50 MB 的文件在中间停止了一段时间