Handling ExecuteScalar() when no results are returned

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

    This is the easiest way to do this...

    sql = "select username from usermst where userid=2"
    object getusername = command.ExecuteScalar();
    if (getusername!=null)
    {
        //do whatever with the value here
        //use getusername.toString() to get the value from the query
    }
    
    0 讨论(0)
  • 2020-11-27 06:24

    I used this in my vb code for the return value of a function:

    If obj <> Nothing Then Return obj.ToString() Else Return "" End If

    0 讨论(0)
  • 2020-11-27 06:26

    SQL NULL value

    • equivalent in C# is DBNull.Value
    • if a NULLABLE column has no value, this is what is returned
    • comparison in SQL: IF ( value IS NULL )
    • comparison in C#: if (obj == DBNull.Value)
    • visually represented in C# Quick-Watch as {}

    Best practice when reading from a data reader:

    var reader = cmd.ExecuteReader();
    ...
    var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());
    

    In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be

    select MAX(ID) from <table name> where <impossible condition>
    

    The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)

    var obj = cmd.ExecuteScalar();
    var result = (obj == null ? -1 : Convert.ToInt32(obj));
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-27 06:28

    /* Select some int which does not exist */
    int x = ((int)(SQL_Cmd.ExecuteScalar() ?? 0));

    0 讨论(0)
  • 2020-11-27 06:31

    The following line:

    string getusername = command.ExecuteScalar();
    

    ... will try to implicitly convert the result to string, like below:

    string getusername = (string)command.ExecuteScalar();
    

    The regular casting operator will fail if the object is null. Try using the as-operator, like this:

    string getusername = command.ExecuteScalar() as string;
    
    0 讨论(0)
提交回复
热议问题