使用SQL datareader在c#中提取1到多个自定义对象

时间:2013-11-07 14:19:59

标签: c# sql sqldatareader

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

我在数据库上有一个名为Airport的自定义对象。但是我无法正确使用datareader。当我尝试将所有机场提取到一个列表中时(参见下面的方法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;
    }
    

1 个答案:

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

使用参数化查询来保证安全。