Handling ExecuteScalar() when no results are returned

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

    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  where 
    
    
    

    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));
    

    提交回复
    热议问题