SQLCommand 和 SqlDataReader 错误

SQLCommand and SqlDataReader error

没有数据时读取无效。

此行出现此错误

string ingredientName = reader2.GetString(0);

我的代码:

var ingredientList = new List<Ingredient>();

SqlCommand staffCommand = new SqlCommand();

string conString = EventsUnlimited.Properties.Settings.Default.DatabaseEventsUnlimitedConnectionString;

using (SqlConnection connection = new SqlConnection(conString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand("SELECT IngredientID, Quantity FROM CourseIngredients WHERE CourseID =" + courseID, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // Obtains the columns from customer
                int ingredientID = reader.GetInt32(0);
                decimal quantity = reader.GetDecimal(1);

                string ingredientNameConstruct;

                SqlCommand ingredientCommand = new SqlCommand();
                string conString2 = EventsUnlimited.Properties.Settings.Default.DatabaseEventsUnlimitedConnectionString;

                using (SqlConnection connection2 = new SqlConnection(conString2))
                {
                    connection2.Open();

                    using (SqlCommand command2 = new SqlCommand ("SELECT IngredientName FROM Stock WHERE IngredientID =" + ingredientID, connection2))
                    {
                        using (SqlDataReader reader2 = command2.ExecuteReader())
                        {
                            string ingredientName = reader2.GetString(0);
                            ingredientNameConstruct = ingredientName;
                        }  
                    }
                }

                ingredientList.Add(new Ingredient(courseID, ingredientNameConstruct, ingredientID, quantity));
            }
        }
    }

    return ingredientList;
}

我不确定是什么导致了这个问题。 table 和我试图从中读取的行中有数据。

在您的 reader2 DataReader 中调用 DataReader.Read 方法以获取结果。

您没有为您的 reader2 对象调用 Read() 方法,它实际上根据返回的结果读取一行,在实际读取列值之前添加:

using (SqlDataReader reader2 = command2.ExecuteReader())
{
      if(reader2.Read()) // this is needed
      {
          string ingredientName = reader2.GetString(0);
          ingredientNameConstruct = ingredientName;
      }
}  

如果您期望多行,则使用 while 循环,如果结果始终是单行,您也可以使用 reader2.ExecuteScalar 作为 @ bradbury9评论中提到:

string ingredientName = command2.ExecuteScalar()?.ToString();
ingredientNameConstruct = ingredientName;