没有数据时无效尝试读取。
此行发生此错误
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;
}
我不确定导致这个问题的原因。表中有数据和我试图读取的行。
你没有为你的Read()
对象调用reader2
方法,它实际上是根据返回的结果读取一行,在实际读取列值之前添加它:
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;
在DataReader.Read DataReader中调用reader2
方法以获得结果。