Handling ExecuteScalar() when no results are returned

后端 未结 22 1097
猫巷女王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:26

    If you either want the string or an empty string in case something is null, without anything can break:

    using (var cmd = new OdbcCommand(cmdText, connection))
    {
        var result = string.Empty;
        var scalar = cmd.ExecuteScalar();
        if (scalar != DBNull.Value) // Case where the DB value is null
        {
            result = Convert.ToString(scalar); // Case where the query doesn't return any rows. 
            // Note: Convert.ToString() returns an empty string if the object is null. 
            //       It doesn't break, like scalar.ToString() would have.
        }
        return result;
    }
    

提交回复
热议问题