1

我遇到了 SQL 阅读器类的问题。

我在数据库上有一个名为 Airport 的自定义对象。但我无法正确使用数据读取器。当我尝试将所有机场提取到列表中时(请参见下面的方法 2),它似乎在将对象添加到列表之前跳过了 while(_reader.Read()) 循环。

有什么建议么?

要提取对象,我使用 3 种方法:

  1. 要查找特定对象:

    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;
    }
    
  2. 将所有机场放入列表

    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;
    }
    
  3. 将其构建到 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;
    }
    
4

1 回答 1

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;
}

使用参数化查询以确保安全。

于 2013-11-07T14:22:19.493 回答