Handling ExecuteScalar() when no results are returned

后端 未结 22 1073
猫巷女王i
猫巷女王i 2020-11-27 05:47

I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:

sql = \"select username from usermst wh         


        
相关标签:
22条回答
  • 2020-11-27 06:33

    I just used this:

        int? ReadTerminalID()
        {
            int? terminalID = null;
    
            using (FbConnection conn = connManager.CreateFbConnection())
            {
                conn.Open();
                FbCommand fbCommand = conn.CreateCommand();
                fbCommand.CommandText = "SPSYNCGETIDTERMINAL";
                fbCommand.CommandType = CommandType.StoredProcedure;
    
                object result = fbCommand.ExecuteScalar(); // ExecuteScalar fails on null
                if (result.GetType() != typeof(DBNull))
                {
                    terminalID = (int?)result;
                }
            }
    
            return terminalID;
        }
    
    0 讨论(0)
  • 2020-11-27 06:33

    Always have a check before reading row.

    if (SqlCommand.ExecuteScalar() == null)
    { 
    
    }
    
    0 讨论(0)
  • 2020-11-27 06:33

    Alternatively, you can use DataTable to check if there's any row:

    SqlCommand cmd = new SqlCommand("select username from usermst where userid=2", conn);
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    adp.Fill(dt);
    string getusername = "";
    // assuming userid is unique
    if (dt.Rows.Count > 0)
        getusername = dt.Rows[0]["username"].ToString();
    
    0 讨论(0)
  • 2020-11-27 06:33

    Slight conjecture: if you check the stack for the exception, it is being thrown then the ADO.NET provider for Oracle is reading the underlying rowset to get the first value.

    If there is no row, then there is no value to find.

    To handle this case execute for a reader and handle Next() returning false for the case of no match.

    0 讨论(0)
提交回复
热议问题