According to MSDN documentation for DbCommand.ExecuteScalar:
If the first column of the first row in the result set is not found, a null reference (Nothing in Visual Basic) is returned. If the value in the database is null, the query returns DBNull.Value.
Consider the following snippet:
using (var conn = new OracleConnection(...)) { conn.Open(); var command = conn.CreateCommand(); command.CommandText = "select username from usermst where userid=2"; string getusername = (string)command.ExecuteScalar(); }
At run-time (tested under ODP.NET but should be the same under any ADO.NET provider), it behaves like this:
- If the row does not exist, the result of
command.ExecuteScalar() is null, which is then casted to a null string and assigned to getusername. - If the row exists, but has NULL in username (is this even possible in your DB?), the result of
command.ExecuteScalar() is DBNull.Value, resulting in an InvalidCastException.
In any case, the NullReferenceException should not be possible, so your problem probably lies elsewhere.
OracleCommandExecuteScalarreturns an object for the result. It's not strongly typed because the SQL statement is arbitrary, so the type isn't known until it's parsed (which is by the DB engine, not by the .NET runtime). The object returned can benull. You are assuming it is a string, and it may well be, and a lot of types can be implicitly converted to such, but it's a very dangerous assumption to make - that object can be of any type. As with any other object reference that you don't explicitly trust, first you should make sure it's notnull.