我正在尝试编写一个方法,该方法应该从数据库中的表中检索多行,并使用这些数据实例化许多对象。然而,据我所知,数据库只返回第一行。当我这样做时:
public static List<Event> getMultipleEvents(string[] eventNames)
{
List<Event> rtnList = new List<Event>();
string EventsToRetrieve = "";
foreach (var item in eventNames)
{
if (EventsToRetrieve != "")
{
EventsToRetrieve += " OR ";
}
EventsToRetrieve += "eventName = '";
EventsToRetrieve += item;
EventsToRetrieve += "' ";
}
// This is the string that the method constructs based on the input i am testing with
//"eventName = 'event six' OR eventName = ' event two' OR eventName = ' event one' OR eventName = ' event seven' "
using (SqlConnection sqlConnection = Globals.GetSqlConnection())
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("SELECT * FROM questions WHERE " + EventsToRetrieve + ";", sqlConnection))
{
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
if (sqlDataReader != null)
{
while (sqlDataReader.Read())
{
Event newEvent = new Event("", DateTime.MinValue, DateTime.MinValue);
string startDateTimeStringFromDB = sqlDataReader["startDateDay"].ToString() + "-" + sqlDataReader["startDateMonth"].ToString() + "-" + sqlDataReader["startDateYear"].ToString();
string endDateTimeStringFromDB = sqlDataReader["endDateDay"].ToString() + "-" + sqlDataReader["endDateMonth"].ToString() + "-" + sqlDataReader["endDateYear"].ToString();
newEvent.EventName = sqlDataReader["eventName"].ToString();
if (DateTime.TryParse(startDateTimeStringFromDB, out DateTime startDateTime))
{
newEvent.StartDate = startDateTime;
}
if (DateTime.TryParse(endDateTimeStringFromDB, out DateTime endDateTime))
{
newEvent.EndDate = endDateTime;
}
rtnList.Add(newEvent);
}
}
}
}
}
return rtnList;
}
有人能向我解释一下我做错了什么吗?我还尝试将while循环包装成do while循环,如下所示。如何从SqlDataReader中读取多个结果集?但这并没有改变任何事情。
您的代码中似乎没有任何错误。但是,我认为您的查询有错误。
首先,在构建SQL查询时,永远不要使用字符串串联。请改用参数化查询。
使用参数化查询,调试SQL语句更加容易,因为它不包括条件字符串连接。