我遇到了SQL阅读器类的问题。
我在数据库上有一个名为Airport的自定义对象。但是我无法正确使用datareader。当我尝试将所有机场提取到一个列表中时(参见下面的方法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;
}
答案 0 :(得分:1)
在第三步中,您再次冒充reader
,这就是为什么当您想要检索所有机场时,您只能获得一个机场。
private Airport BuildAirport(SqlDataReader _reader)
{
Airport temAirport = new Airport();
temAirport.airportCode = (string) _reader["airportCode"];
temAirport.airportName = (string) _reader["airportName"];
temAirport.country = (string) _reader["country"];
temAirport.city = (string) _reader["city"];
return temAirport;
}
现在我们必须更改您的第一种方法,因为更改BuildAirport
会破坏它。我们现在必须在FindAirportByCode
中阅读一行。
public Airport FindAirportByCode(string _airportCode)
{
con.Open();
string query = "SELECT * from Airport WHERE airportCode = @airportCode";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@airportCode", _airportCode);
SqlDataReader _reader = cmd.ExecuteReader();
Airport retAirport = null;
if (_reader.Read())
{
retAirport = BuildAirport(_reader);
}
_reader.Close();
con.Close();
return retAirport;
}
使用参数化查询来保证安全。