网络核心-Sql数据读取器突然为空

时间:2018-08-12 04:09:38

标签: c# asp.net-core .net-core

  

NullReferenceException:对象引用未设置为对象的实例。   在(rdr2.Read())时在线LabsDal.cs中的WebApplication1.Controllers.LabsDal.GetDefinition(string connectionString,string key)

conn.Open();
using (var cmd = new SqlCommand("Lab_GetDefinitionList", conn))
{
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@key", key);
    SqlDataReader rdr2 = cmd.ExecuteReader(System.Data.CommandBehavior.SingleResult);
    while (rdr2.Read())  // <---- ERROR HERE
    {
        result.Elements.Add(rdr2.GetString(0));
    }
}

我尝试了许多变化,但没有取得任何进展。在其他地方,等效代码也可以正常工作。

2 个答案:

答案 0 :(得分:2)

您需要检查IsDBNull:

rdr2.Read()
if(rdr2.HasRows)
{
    if(!rdr2.IsDBNull(colIndex))
       result.Elements.Add(rdr2.GetString(colIndex));
}

或者您可以使用SqlDataAdapter

using (SqlCommand cmd = new SqlCommand())
            {
                DataSet ds = new DataSet();
                cmd.Connection = new SqlConnection(connectionString);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandTimeout = 900;
                cmd.CommandText = "Lab_GetDefinitionList";
                cmd.Parameters.AddWithValue("@key", key);

                cmd.Connection.Open();
                //
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;

                da.Fill(ds);
                cmd.Connection.Close();

                // **check if return data**
                if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                     result.Elements.Add(ds.Tables[0].Rows[0]["YourColumnName"].ToString());

            }

答案 1 :(得分:1)

要检查是否为空,请尝试以下操作:

username = browser.find_element_by_id('loginEmail')
username.send_keys(usernameStr)

password = browser.find_element_by_id('loginPw')
password.send_keys(passwordStr)

signInButton = browser.find_element_by_xpath(
"//button[@type='submit']")
signInButton.click()