处理的ExecuteScalar()时,不返回任何结果 [英] Handling ExecuteScalar() when no results are returned

查看:150
本文介绍了处理的ExecuteScalar()时,不返回任何结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的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 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.

在任何情况下,的NullReferenceException 应该是不可能的,所以你的问题很可能出在其它地方。

In any case, the NullReferenceException should not be possible, so your problem probably lies elsewhere.

这篇关于处理的ExecuteScalar()时,不返回任何结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆