SQLDataReader does not identify the empty columns

扶醉桌前 提交于 2019-12-12 02:49:48

问题


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:


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;


来源:https://stackoverflow.com/questions/32988881/sqldatareader-does-not-identify-the-empty-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!