【问题标题】:if record not found in database I want to post out not found but seem not to be working [duplicate]如果在数据库中找不到记录,我想发布找不到但似乎没有工作[重复]
【发布时间】:2018-05-23 11:06:09
【问题描述】:
while (reader.Read())
{
    var g = reader.FieldCount;
    if (g > 0)
    {
        string a = reader.GetString(1);
        string b = reader.GetString(3);
        string c = reader.GetString(4);
        string d = reader.GetString(5);

        await context.PostAsync($" ### Please find below the fleet policy information \n #### Policy number - " +
        $"`{a}` \n #### Policy type - `{b}` \n #### Property - `{c}` \n #### Number - `{d}` ");
    }
    else
    {
         await context.PostAsync("Record not found");
    }
}

如果数据库中不存在记录,我希望机器人显示未找到记录,但它似乎不起作用,而是什么都不显示。

【问题讨论】:

    标签: c# botframework


    【解决方案1】:

    reader.Read() 表示数据集中有实际记录。你应该把你的代码放在while之外。

    【讨论】:

      【解决方案2】:

      您改为检查属性 HasRows

      if(reader.HasRows)
      {
           while (reader.Read())
           {
               string a = reader.GetString(1);
               string b = reader.GetString(3);
               string c = reader.GetString(4);
               string d = reader.GetString(5);
      
               await context.PostAsync(...........);
           }
      }
      else
      {
          await context.PostAsync("Record not found");
      }
      

      当没有更多记录要读取时,实际读取返回 false。如果您没有任何要读取的记录,该方法会立即返回 false 并且您永远不会进入读取循环,您有代码来输出您的消息。当然 FieldCount 在这里没有任何意义,因为它计算的是字段而不是 Read 方法返回的 IDataRecord 的行。

      因此,您的解决方案是在开始循环之前检查 HasRows 属性,如果它返回 false,则打印您的消息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多