SQLDataReader无法识别空列 [英] SQLDataReader does not identify the empty columns

查看:113
本文介绍了SQLDataReader无法识别空列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个函数可以读取查询结果,该查询稍后将在程序上使用,如下所示:

So, I have a function which reads the result of a query that is used later on the program as it follows:

connection.Open();
int combination;
using (SqlCommand com1 = new SqlCommand())
{
    com1.Connection = connection; 
    com1.CommandText = "select FinalComboId from relationTable where sourceCombo=@source and destinationCombo=@destination";
    com1.Parameters.Add(new SqlParameter("@source",combo.ToString() ?? ""));
    com1.Parameters.Add(new SqlParameter("@destination", destination ?? ""));
    SqlDataReader comboLinkReader = com1.ExecuteReader();
    if (!comboLinkReader.Read() || comboLinkReader.FieldCount==0)
    {
        ScriptManager.RegisterClientScriptBlock(this, GetType(),
                   "alertMessage", @"alert('Combination does not exists,please contact admin!')", true);
    }
    else 
    {
        combination = Convert.ToInt32(comboLinkReader["FinalComboId"]);

    }
}

我想实现的是:如果结果为空,则执行警报脚本,否则将结果另存为整数,以用于进一步的计算。我遵循了有关该问题的一些教程和示例,并且当我第二天执行该函数时,它运行良好。现在,从启动到生产两个小时,它不会计算第一个条件:

What I would like to achieve is: if the result is empty, than execute the alert script, else save the result as an integer, that will be used for further calculations. I have followed several tutorials and examples regarding that issue, and when I executed the function the other day, it worked just fine. Now, 2 hours from launching it to production, it does not calculate the first condition:

if (!comboLinkReader.Read() || comboLinkReader.FieldCount==0)
       {//calculations  here}

我有还尝试了

if (!comboLinkReader.Read() || comboLinkReader.IsDbNull(0))
   {//calculations}

我也遇到了同样的问题。查询应返回一个单一值。
我做错什么了吗?

and I have the same problem. The query should return one single value. Is there something that I am doing wrong?

推荐答案

IsDbNull 是需要为列索引提供参数的方法。

IsDbNull is a method that needs an argument for the column index.

int? finalComboId = null;
if(comboLinkReader.Read() && !comboLinkReader.IsDbNull(0))
    finalComboId = comboLinkReader.GetInt32(0);
if(!finalComboId.HasValue)
    ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", @"alert('Combination does not exists,please contact admin!')", true);
else 
    combination = finalComboId.Value;

这篇关于SQLDataReader无法识别空列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆