C#中的DataReader异常

时间:2016-04-02 11:24:31

标签: c#

首先让我解释一下我的代码。

  1. 获取所选目的地的票价(reader1)
  2. 为所选用户ID(reader2)提取*
  3. 插入数据以处理新余额(cmd3)
  4. 将新余额检索为计算字段(reader3)
  5. 更新旅行帐户(cmd5)
  6. 清除calc_tb以获取下一个客户输入(cmd6)
  7. 我的问题是在运行时,我收到此错误:

      

    已经有一个与此命令关联的打开DataReader,必须先关闭它。

    如何处理多个访问不同表的DataReaderDataReader与Java中的结果集类似吗?

    我是编码的初学者。

            string id, 
            destin, num;
            id = txt_id.Text;
            destin = cb_destin.Text;
            num = cb_num.Text;
    
    
    
            string sql1 = "SELECT fare FROM route_info WHERE route_name='" +destin + "' ";
            string sql2 = "SELECT * FROM trav_acc WHERE user_id='" + id + "'";
    
            con.Open();
    
            cmd1 = new SqlCommand(sql1, con);
            reader1 = cmd1.ExecuteReader();
    
            while(reader1.Read())
            {
    
                string fare = (string)reader1["fare"];
    
                cmd2 = new SqlCommand(sql2, con);
                reader2 = cmd2.ExecuteReader();
                string cur_bal = (string)reader2["cur_bal"];
                reader2.Close();
    
                string calc1 = "INSERT INTO calc_tb VALUES('" + cur_bal + "','" + num + "','" + fare + "')";
                string calc2 = "SELECT cur_bal - (nof_tickets * fare) AS new_bal FROM calc_tb";
    
                cmd3 = new SqlCommand(calc1, con);
                cmd3.ExecuteNonQuery();
    
                cmd4 = new SqlCommand(calc2, con);
                reader3 = cmd4.ExecuteReader();
    
                while(reader3.Read())
                {
                    string new_bal = (string)reader3["new_bal"];
    
                    string update = "UPDATE trav_acc SET cur_bal='" + new_bal + "',last_bal='" + cur_bal + "' WHERE user_id='" + id + "'  ";
                    cmd5 = new SqlCommand(update, con);
                    cmd5.ExecuteNonQuery();
    
                    string clear = "DELETE FROM calc_tb";
                    cmd6 = new SqlCommand(clear, con);
                    cmd6.ExecuteNonQuery();
                }
    
            }
            con.Close();
            MessageBox.Show("Thank you for using EasyTravel.Come again soon!");
    
    
    
        }
    

1 个答案:

答案 0 :(得分:0)

似乎reader3cmd4是在您向我们展示的代码之外定义的,但至少它们是在reader1的循环之外定义的。因此,如果您的reader1包含多行,则reader3cmd4将再次分配,但是" old" reader3永远不会关闭。完成阅读后关闭reader3。或者使用using语句,它将自动处理结束。

using (DataReader reader1 = cmd1.ExecuteReader()) {
    ....
    while (reader1.Read()) {
        ....
        using (DataReader reader3 = cmd4.ExecuteReader()) {
            while (reader3.Read()) {
            }
        }  //reader3 is closed here automatically
    }
} //reader1 is closed here automatically

此外,我不确定我是否记得正确,但我认为在同一个连接上不可能有两个开放阅读器。不过,我可能错了。