我遇到了 SQL 阅读器类的问题。
我在数据库上有一个名为 Airport 的自定义对象。但我无法正确使用数据读取器。当我尝试将所有机场提取到列表中时(请参见下面的方法 2),它似乎在将对象添加到列表之前跳过了 while(_reader.Read()) 循环。
有什么建议么?
要提取对象,我使用 3 种方法:
要查找特定对象:
public Airport FindAirportByCode(string _airportCode) { con.Open(); string query = "SELECT * from Airport WHERE airportCode = '" + _airportCode + "'"; SqlCommand cmd = new SqlCommand(query, con); SqlDataReader _reader = cmd.ExecuteReader(); Airport retAirport = BuildAirport(_reader); _reader.Close(); con.Close(); return retAirport; }
将所有机场放入列表
public List<Airport> SelectAll() { con.Open(); List<Airport> airports = new List<Airport>(); string query = "SELECT * from Airport"; SqlCommand cmd = new SqlCommand(query, con); SqlDataReader _reader = cmd.ExecuteReader(); while (_reader.Read()) { Airport temAirport = new Airport(); temAirport = BuildAirport(_reader); airports.Add(temAirport); // It seems to skip this step and only add the last Airport from BuildAirport to the list. } _reader.Close(); con.Close(); return airports; }
将其构建到 C# 中的对象中
private Airport BuildAirport(SqlDataReader _reader) { Airport temAirport = new Airport(); while (_reader.Read()) { temAirport.airportCode = (string) _reader["airportCode"]; temAirport.airportName = (string) _reader["airportName"]; temAirport.country = (string) _reader["country"]; temAirport.city = (string) _reader["city"]; } _reader.Close(); return temAirport; }