SQLDataReader does not identify the empty columns

2019-09-07 15:58发布

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}

I have also tried with

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?

1条回答
做自己的国王
2楼-- · 2019-09-07 16:32

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;
查看更多
登录 后发表回答