Handling ExecuteScalar() when no results are returned(没有返回结果时处理 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:对象引用未设置为对象的实例
当userid=2的数据库表中没有行时会发生此错误.
这种情况应该怎么处理?
This error occurs when there is no row in the database table for userid=2.
How should I handle this situation?
推荐答案
根据DbCommand.ExecuteScalar 的 MSDN 文档:
如果没有找到结果集中第一行的第一列,则返回空引用(在 Visual Basic 中为 Nothing).如果值在数据库为空,查询返回 DBNull.Value.
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.
考虑以下代码段:
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()的结果为null,然后将其转换为空字符串并分配给getusername.李> - 如果该行存在,但用户名中有 NULL(这在您的数据库中是否可能?),
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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:没有返回结果时处理 ExecuteScalar()
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
