【问题标题】:Getting an error with data reader数据阅读器出错
【发布时间】:2013-12-11 12:49:31
【问题描述】:

我正在尝试使用 datareader 从 sql 数据库中获取数据,以将它们放入组合框中,但在此代码中出现错误:阅读器关闭时调用读取无效。 错误出现在 while 语句的第二部分代码中。它是表单加载的代码。

class DataLoad
{  
    public SqlDataReader comboboxLoad()
    {
        SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
        SqlCommand com = new SqlCommand();
        com.Connection = con;
        SqlDataReader dr;
        com.CommandText = "select drugname from drugtab order by drugname";
        con.Open();
        dr = com.ExecuteReader();
        con.Close();
        return dr;
    }
}



private void Smart_Pharmacy_Load(object sender, EventArgs e)
    {
        DataLoad d = new DataLoad();
        SqlDataReader DR = d.comboboxLoad();

        while (DR.Read())
        {          
            DrugNameCombo.Items.Add(DR["drugname"]);
        }
    }

【问题讨论】:

  • 方法comboboxLoad是多余的。至少您还应该添加将项目添加到组合框中的代码。这将修复错误并证明方法的名称是正确的。

标签: c#


【解决方案1】:

您关闭了与此行的连接:con.Close()

您需要保持打开状态,直到您读完为止。尝试使用using 语句:

// Open your connection here
SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
con.Open();
// The using statement declares that you want to use the SqlDataReader for a certain
// block of code. Can be used because it implements IDisposable
using(SqlDataReader DR = d.comboboxLoad(con)) {
    while (DR.Read())
    {          
        DrugNameCombo.Items.Add(DR["drugname"]);
    }
}
// When we reach here, the SqlDataReader will be disposed

// Could do some more work here

// Finally close the connection
con.Close();

您需要更新您的 comboboxLoad 以支持这种新的工作方式

public SqlDataReader comboboxLoad(SqlConnection con)
{
    SqlCommand com = new SqlCommand();
    com.Connection = con;
    com.CommandText = "select drugname from drugtab order by drugname";
    return com.ExecuteReader();
}

【讨论】:

  • 或者干脆将DrugNameCombo.Items.Add-code 移到comboboxLoad 方法中,改成void
  • 或者...这会更有意义,但我认为如果我保持相同的结构,它会突出原始代码的问题。
【解决方案2】:

问题是,您正在关闭函数comboboxLoad() 中的连接con.Close();。阅读器需要打开与数据库的连接才能工作。

您应该在处理完 dataReader 后关闭连接。

【讨论】:

    猜你喜欢
    • 2012-07-28
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2018-03-04
    相关资源
    最近更新 更多