处理的ExecuteScalar()时,不返回任何结果 [英] Handling ExecuteScalar() when no results are returned
问题描述
我使用下面的SQL查询和的ExecuteScalar()方法来从一个Oracle数据库中的数据:
I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:
sql = "select username from usermst where userid=2"
string getusername = command.ExecuteScalar();
它显示我此错误消息:
It is showing me this error message:
System.NullReferenceException:对象未设置为一个对象的实例的
当没有在数据库表中没有行会出现此错误用户ID = 2
This error occurs when there is no row in the database table for userid=2
我应该如何处理这种情况?
How should I handle this situation?
推荐答案
据的 MSDN文档DbCommand.ExecuteScalar :
如果没有找到结果集中的第一行的第一列,空引用(在Visual Basic中为Nothing),则返回。如果在数据库中的值为null,该查询返回的DBNull.Value 。的
考虑下面的代码片段:
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();
}
在运行时(在ODP.NET测试,但应该是在任何ADO.NET提供相同的),它的行为是这样的:
At run-time (tested under ODP.NET but should be the same under any ADO.NET provider), it behaves like this:
- 如果该行不存在,结果
command.ExecuteScalar()
为空,然后浇铸到一个空字符串并分配给getusername
。 - 如果该行存在,但在用户名都是空(这甚至可能在你的数据库?),
的结果command.ExecuteScalar()
是的DBNull.Value
,导致InvalidCastException的
。
- If the row does not exist, the result of
command.ExecuteScalar()
is null, which is then casted to a null string and assigned togetusername
. - If the row exists, but has NULL in username (is this even possible in your DB?), the result of
command.ExecuteScalar()
isDBNull.Value
, resulting in anInvalidCastException
.
在任何情况下,的NullReferenceException
应该是不可能的,所以你的问题很可能出在其它地方。
In any case, the NullReferenceException
should not be possible, so your problem probably lies elsewhere.
这篇关于处理的ExecuteScalar()时,不返回任何结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!