【问题标题】:how can I store value from sqlDataReader? and to compare?如何存储来自 sqlDataReader 的值?并进行比较?
【发布时间】:2011-10-23 13:24:16
【问题描述】:
int availableSeat = 0;
string query = "select flight_no flight_seat from flight_info where flight_departure_time = @selectedFlight AND flight_from = @flightFrom AND flight_to = @flightTo ";
string url = "Server=localhost;Database=flight;uid=******;password=*****";
con1 = new MySqlConnection(url);
con1.Open();
cmd1 = new MySqlCommand(query,con1);
cmd1.Parameters.AddWithValue("@selectedFlight",comboBox3.SelectedItem);
cmd1.Parameters.AddWithValue("@flightFrom",comboBox1.SelectedItem);
cmd1.Parameters.AddWithValue("@flightTo",comboBox2.SelectedItem);
reader = cmd1.ExecuteReader();
while (reader.Read()) 
{
    availableSeat.Equals(reader["flight_seat"]);
    if(availableSeat > 0)
    {
        MessageBox.Show("The seat is available!!");
    }
    else
    {
        MessageBox.Show("Sorry, all seat has been booked!!");
    }
}
con1.Close();

正如您在此处看到的,我想将 SQL 中的 flight_seat 列存储到 availableSeat 中,以检查是否有空位。

我该怎么做?因为它一直在其他地方。

【问题讨论】:

    标签: c# mysql datareader


    【解决方案1】:

    availableSeat.Equals() 是比较而不是赋值。您需要分配该值。例如

    availableSeat = (int)reader["flight_seat"];
    

    【讨论】:

      【解决方案2】:

      改成:

      availableSeat = (int)reader["flight_seat"]);
      

      Equals() 方法用于比较目的(相等)而不是赋值。此外,在 C# 中,通过将 = 左侧的变量设置为右侧语句的结果来完成赋值。

      您需要将reader 中的值转换为int,因为它存储为object。您还应该检查 null 值,因为它来自数据库:

      availableSeat = reader["flight_seat"].Equals(DBNull.Value)
                          ? 0
                          : (int)reader["flight_seat"];
      

      【讨论】:

      • 嗯,我觉得有问题。它说“抛出了 System.invalidCaseException 类型的异常:\n指定的强制转换无效”
      • 那么您的flight_seat 不是int 值。您应该检查 MySQL 数据库中的底层类型。例如,如果它是某种类型的 varchar,则需要将 availableSeat 定义为 string
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      相关资源
      最近更新 更多