【问题标题】:Reader is empty阅读器为空
【发布时间】:2017-11-16 13:28:23
【问题描述】:

我有一个数据阅读器得到空结果,但我不明白为什么?

我的连接状态是打开的,我在我的数据库中测试了我的查询,它返回值但是我的 reader.read() 只是被跳过了

OdbcDataReader Reader;
string mond = "select fir_mdnt from safir JOIN safirbpv ON firbpv_fir = fir_fir where firbpv_ibnr = '" + _cb_Compte.SelectedItem + "' group by fir_mdnt;";
OdbcCommand mondant = new OdbcCommand(mond, InfoConnexion);

InfoConnexion.Open();
Reader = mondant.ExecuteReader();
while (Reader.Read())
{
    MessageBox.Show(Reader.ToString());
}
InfoConnexion.Close();

【问题讨论】:

  • 你是 sql 语句返回行吗?似乎sql查询不返回任何与“_cb_Compte.SelectedItem”匹配的行
  • 检查 _cb_Compte.SelectedItem 值,提取选择查询并检查数据库是否返回任何值。这将确认问题是否与 .NET 代码有关,或者数据库中没有具有此类过滤器值的记录。
  • 首先,USE PARAMETERISED QUERIES,很抱歉大喊大叫,但这非常重要,不仅是为了安全,而且对于查询计划的重用和防止可能的数据截断和转换错误。您是否尝试过调试以查看该命令发出的确切查询?
  • 当我使用逐步调试时,我的查询看起来像这样: select fir_mdnt from safir JOIN safirbpv ON firbpv_fir = fir_fir where firbpv_ibnr = 'CH1200767000A07116162' group by fir_mdnt;当我在我的数据库中尝试它时,它会返回我想要的,一个 int。
  • “跳过”到底是什么意思? Reader.Read() 是否返回 false 或者您的意思是该行甚至从未执行过?如果是后者,那么你抛出了一个你在任何地方都没有捕捉到的异常。

标签: c# sql odbc datareader


【解决方案1】:

刷新例程并在using (OdbcDataReader reader = mondant.ExecuteReader()) {

上放置一个断点

代码被清除

//DONE: make SQL readable
//DONE: make SQL parametrized (ODBC doesn't support named parameters, but ?)
string sql = 
    @"select fir_mdnt 
        from safir join 
             safirbpv on firbpv_fir = fir_fir 
       where firbpv_ibnr = ?
    group by fir_mdnt";

//DONE: wrap IDisposable into using
//DONE: do not share the connection but create a new one
using (OdbcConnection con = new OdbcConnection(connectionStringHere)) {
  con.Open();

  //DONE: wrap IDisposable into using
  using(OdbcCommand mondant = new OdbcCommand(sql, con)) {
    //TODO: check the actual parameter type and value
    //TODO: you may want to add Trim: _cb_Compte.SelectedItem.ToString().Trim() 
    mondant.Parameters.Add(new OdbcParameter("", OdbcType.Text) 
      {Value = _cb_Compte.SelectedItem}); 

    //DONE: wrap IDisposable into using
    //TODO: put a break point here
    using (OdbcDataReader reader = mondant.ExecuteReader()) {
      while (reader.Read()) {
        MessageBox.Show(Convert.ToString(reader[0]));
      }
    }
  } 
}

然后你必须调试

  • 运行代码。
  • 断点处停止。
  • 检查sql,参数(其值)。
  • 检查reader.HasRows 值。
  • 在任何类型的 RDMBS 编辑器中执行查询:是否返回了任何记录?

【讨论】:

  • 我像你说的那样清理了我的代码,我还删除了_cb_Compte.SelectedItem 中的所有空间,现在它可以工作了。谢谢
猜你喜欢
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2019-06-04
  • 2016-02-29
  • 2011-04-01
相关资源
最近更新 更多