1

I have a table name

flight_info (flight_id, flight_no, depart_from, destination, depart_time, arrive_time)

Now I want to retrieve only

flight_id on the basis of column depart_from and destination

I wrote the SQL as following:

string str = "SELECT fligth_id FROM flight_info WHERE  depart_from = @depart AND destination = @destination"

While running, it's showing an error pointing @depart and @destination. Can you help me, How can I specify those scalar variable.?

I tried it..

SqlDataReader myReader;
string depart = myReader["depart_from"].ToString();
string destination = myReader["destination"].ToString();

But, it's not working. Help needed.

4

1 回答 1

1

您在查询中使用了参数,但没有指定它们。

试试这样;

using (SqlConnection connection = new SqlConnection(connectionString))
{
   connection.Open();
   using (SqlCommand command = new SqlCommand("SELECT fligth_id FROM flight_info WHERE  depart_from = @depart AND destination = @destination", connection))
   {
        command.Parameters.Add("@depart", depart);
        command.Parameters.Add("@destination", destination);
        SqlDataReader myReader = command.ExecuteReader();
        while (myReader.Read())
        {
           int fligth_id = reader.GetInt32(0);
        }
   }
}

由于您的查询仅返回fligth_id列,因此您无法以这种方式访问depart_from​​和destination列。逐一SqlDataReader读取数据库行。

如果您在查询中返回其他列,例如;

SELECT fligth_id, depart_from, destination

你可以用同样的方式阅读它们;

while (myReader.Read())
{
    int fligth_id = reader.GetInt32(0);
    string depart_from = reader.GetString(1);
    string destination = reader.GetString(2);
}
于 2013-04-24T06:05:36.510 回答