数据读取器有行,但其值的比较永远不会为真

本文关键字:永远 比较 读取 数据 | 更新日期: 2023-09-27 18:36:44

我正在创建一个用于预订酒店房间的模块。选择房间后,房间号将显示在标签中。单击"确定"按钮时,将执行以下代码。当我检查房间的可用性时,即使它是"否",标志也不会初始化为 1。谁能指导我哪里出错了。

protected void ok_room(object sender, EventArgs e)
{
    if (Label1.Text != "")
    {
        int result = 0;
        int flag = 0;
        string[] room = Label1.Text.Split(new char[] { ' ' });
        cmd = new SqlCommand();
        cmd1 = new SqlCommand();
        cmd1.Connection = con;
        cmd.Connection = con;
        for (int i = 0; i < room.Length; i++)
        {
            cmd1.CommandText = "select room_availability from rooms where room_num='" + room[i] + "'  ";
            dr = cmd1.ExecuteReader();
            while (dr.Read())
            {
                if (dr[0].ToString().Equals("No"))//this is not working
                    flag = 1;
            }
            dr.Close();
        }
        Response.Write(flag);
        if (flag == 0)
        {
            for (int i = 0; i < room.Length; i++)
            {
                cmd.CommandText = "update rooms set room_availability='No' where room_num='" + room[i] + "'";
                cmd.ExecuteNonQuery();
                result = 1;
            }
        }
        else
        {
            Label2.Text = "Some of the selected rooms are not available. Kindly try again";
            Label1.Visible=false;
        }
        if (result == 1)
        {
            isRoomAvailable = true;
            Label2.Text = " Room(s) " + Label1.Text + " is/are booked";
            Label1.Visible = false;
        }
    }
    else
        Response.Write("<script>alert('Select a room first.')</script>");
}

数据读取器有行,但其值的比较永远不会为真

I would do more of the logic in SQL, this would simplify the code:
// Create a condition looking like this: room_num IN('1', '2', '3')
string roomsCondition = "room_num IN (' + Label1.Text.Replace(" ", "', '") + "')";
cmd1.CommandText =
    @"SELECT SUM(CASE WHEN room_availability='Yes' THEN 1 ELSE 0 END) As available,
    SUM(CASE WHEN room_availability='No' THEN 1 ELSE 0 END) As not_available
    FROM rooms WHERE " + roomsCondition;

此查询返回可用和不可用房间的数量。然后,制定逻辑应该比使用标志更容易。

另请查看ExecuteScalar方法。它使它比我上面显示的查询更容易:

using (SqlConnection conn = new SqlConnection(connString)) {
    string sql = "SELECT COUNT(*) FROM rooms WHERE room_availability='Yes' AND " +
                 roomsCondition;
    SqlCommand cmd = new SqlCommand(sql, conn);
    conn.Open();
    int availableRooms = (int)cmd.ExecuteScalar();
    if (availableRooms > 0) {
        cmd.CommandText =
            @"UPDATE rooms
            SET room_availability='No'
            WHERE availability='Yes' AND " + roomsCondition;
        cmd.ExecuteNonQuery();
    } else {
        ...
    }
}