根据DbCommand.ExecuteScalar的MSDN文档 :

如果结果集中第一行的第一列未find,则返回null引用(在Visual Basic中为Nothing)。 如果数据库中的值为空,则查询返回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下testing,但在任何ADO.NET提供者下应该是一样的),它的行为如下:

如果该行不存在,则command.ExecuteScalar()的结果为空,然后将其转换为空string并分配给getusername 。

如果行存在,但在用户名中有NULL(这在数据库中甚至可能?), command.ExecuteScalar()的结果是DBNull.Value ,导致InvalidCastException 。

无论如何, NullReferenceException应该是不可能的,所以你的问题可能在别处。

首先你应该确保你的命令对象不为空。 然后你应该设置命令的CommandText属性到你的SQL查询。 最后,你应该把返回值存储在一个对象variables中,并在使用它之前检查它是否为null:

command = new OracleCommand(connection) command.CommandText = sql object userNameObj = command.ExecuteScalar() if userNameObj != null then string getUserName = userNameObj.ToString() ...

我不确定VB的语法,但你明白了。

我只是用这个:

int? ReadTerminalID() { int? terminalID = null; using (FbConnection conn = connManager.CreateFbConnection()) { conn.Open(); FbCommand fbCommand = conn.CreateCommand(); fbCommand.CommandText = "SPSYNCGETIDTERMINAL"; fbCommand.CommandType = CommandType.StoredProcedure; object result = fbCommand.ExecuteScalar(); // ExecuteScalar fails on null if (result.GetType() != typeof(DBNull)) { terminalID = (int?)result; } } return terminalID; }

以下行:

string getusername = command.ExecuteScalar();

…将尝试隐式地将结果转换为string,如下所示:

string getusername = (string)command.ExecuteScalar();

如果对象为null,常规的转换运算符将失败。 尝试使用as-operator,如下所示:

string getusername = command.ExecuteScalar() as string;

sql = "select username from usermst where userid=2" var _getusername = command.ExecuteScalar(); if(_getusername != DBNull.Value) { getusername = _getusername.ToString(); }

这可以帮助..例如::

using System; using System.Data; using System.Data.SqlClient; class ExecuteScalar { public static void Main() { SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;"); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee"; mySqlConnection.Open(); int returnValue = (int) mySqlCommand.ExecuteScalar(); Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue); mySqlConnection.Close(); } }

从这里

在阅读行之前,一定要检查一下。

if (SqlCommand.ExecuteScalar() == null) { }

在你的情况下,logging不存在于userid=2或者它可能在第一列中包含空值,因为如果在SQL命令中使用的查询结果没有find值, ExecuteScalar()返回null 。

这是做这个最简单的方法…

sql = "select username from usermst where userid=2" object getusername = command.ExecuteScalar(); if (getusername!=null) { //do whatever with the value here //use getusername.toString() to get the value from the query }

或者,您可以使用DataTable来检查是否有任何行:

SqlCommand cmd = new SqlCommand("select username from usermst where userid=2", conn); SqlDataAdapter adp = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); adp.Fill(dt); string getusername = ""; // assuming userid is unique if (dt.Rows.Count > 0) getusername = dt.Rows[0]["username"].ToString();

轻微的猜想:如果您检查堆栈的exception,它正在被抛出然后ADO.NET提供程序的Oracle正在读取底层的行集以获得第一个值。

如果没有行,那么没有价值可以find。

为了处理这种情况,为读者执行并处理Next() ,如果不匹配,则返回false。

我使用它与Microsoft应用程序块DLL(它是DAL操作的帮助库)

public string getCopay(string PatientID) { string sqlStr = "select ISNULL(Copay,'') Copay from Test where patient_id=" + PatientID ; string strCopay = (string)SqlHelper.ExecuteScalar(CommonCS.ConnectionString, CommandType.Text, sqlStr); if (String.IsNullOrEmpty(strCopay)) return ""; else return strCopay ; }

我在VS2010中看到string getusername = command.ExecuteScalar(); 给出编译错误, 不能隐式地将types对象转换为string 。 所以你需要写string getusername = command.ExecuteScalar().ToString(); 当在数据库中没有findlogging时,它给出错误的对象引用没有设置为一个对象的实例,当我注释“.ToString()”,它不会给出任何错误。 所以我可以说ExecuteScalar不会抛出exception。 我认为@Rune Grimstad提供的是正确的。

当连接到数据库的用户具有CONNECT权限但没有从数据库中读取权限时,我遇到了这个问题。 就我而言,我什至不能做这样的事情:

object userNameObj = command.ExecuteScalar()

把它放在一个try / catch中(你应该可以这样做),这是我看到处理权限不足问题的唯一方法。

private static string GetUserNameById(string sId, string connStr) { System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr); System.Data.SqlClient.SqlCommand command; try { // To be Assigned with Return value from DB object getusername; command = new System.Data.SqlClient.SqlCommand(); command.CommandText = "Select userName from [User] where userid = @userid"; command.Parameters.AddWithValue("@userid", sId); command.CommandType = CommandType.Text; conn.Open(); command.Connection = conn; //Execute getusername = command.ExecuteScalar(); //check for null due to non existent value in db and return default empty string string UserName = getusername == null ? string.Empty : getusername.ToString(); return UserName; } catch (Exception ex) { throw new Exception("Could not get username", ex); } finally { conn.Close(); } }

/ *select一些不存在的int * /

int x =((int)(SQL_Cmd.ExecuteScalar()?? 0));

我在我的VB代码中使用这个函数的返回值:

如果obj <> Nothing Then返回obj.ToString()否则返回“”End If

试试这个代码,它似乎解决了你的问题。

Dim MaxID As Integer = Convert.ToInt32(IIf(IsDBNull(cmd.ExecuteScalar()), 1, cmd.ExecuteScalar()) )

我正在使用Oracle 。 如果你的sql返回数值,即int,你需要使用Convert.ToInt32(object)。 这里是下面的例子:

public int GetUsersCount(int userId) { using (var conn = new OracleConnection(...)){ conn.Open(); using(var command = conn.CreateCommand()){ command.CommandText = "select count(*) from users where userid = :userId"; command.AddParameter(":userId", userId); var rowCount = command.ExecuteScalar(); return rowCount == null ? 0 : Convert.ToInt32(rowCount); } } }

尝试这个

sql = "select username from usermst where userid=2" string getusername = Convert.ToString(command.ExecuteScalar());

c# mysql executescalar为什么返回值是空_当没有结果返回时处理ExecuteScalar()相关推荐

  1. mysql insert 返回值是什么_各种SQL Insert 返回值

    declare v_id t.id%type; begin insert into t(id) values(seq.nextval) returning id into v_id; end; / d ...

  2. 调用个别f5 负载端口为80的vs时,返回值为空的问题

    现状: vs负载端口为80并添加XFF,pool包含2个member,member的monitor端口为80&9000. 故障现象: 应用同事描述说再完全复制了一个member并添加到pool ...

  3. mock如何为空_Mockito怎么样Mock返回值为空的方法

    [在前面文章中,讨论了如何直接减少构造函数和方法的参数,比如通过自定义类型.引入参数对象.Builder模式.重载和方法命名来减少参数.你可能会奇怪为什么会讨论方法返回 Mockito怎么样Mock返 ...

  4. IntelliJ IDEA设置方法注释模板并解决入参和返回值为空问题

    ## 简介 网上讲解设置方法注释模板的文章很多,尝试了很多方法后,发现在方法体外生成的模板入参值和返回值都是null,而放到方法体内的入参值和返回值就可以自动生成.苦试N次,终于发现诀窍.Idea的这 ...

  5. DataFrame计算corr()函数计算相关系数时,出现返回值为空或NaN的情况

    1. 返回值为空的情况 出现返回值为空的情况是因为数据的类型不是数值型.用data.info()函数可以查看dataframe的信息.这里举个例子: ###创建一个dataframe,数据类型为obj ...

  6. 获取返回值作为变量_解决多线程间共享变量线程安全问题的大杀器——ThreadLocal...

    微信公众号:Zhongger 我是Zhongger,一个在互联网行业摸鱼写代码的打工人! 关注我,了解更多你不知道的[Java后端]打工技巧.职场经验等- 上一期,讲到了关于线程死锁.用户进程.用户线 ...

  7. python返回值return用法_Python中return函数返回值代码实例用法

    本篇文章小编给大家分享一下Python中return函数返回值代码实例用法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. return 添加返回值 r ...

  8. linux 变量函数返回值,linux shell 自定义函数(定义、返回值、变量作用域)介绍...

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用.下面说说它的定义方法,以及调用需要注意那些事项. 一.定义shell函数(define function) 语法: [ f ...

  9. 创建一个Python脚本,实现以下功能。(1)定义一个函数,用于计算圆柱体的表面积、体积,函数名为comput,.输入参数为底半径(r)、高(h),返回值为表面积(S)、体积(V),返回多值的函

    创建一个Python脚本,实现以下功能. (1)定义一个函数,用于计算圆柱体的表面积.体积,函数名为comput,.输入参数为底 半径(r).高(h),返回值为表面积(S).体积(V),返回多值的函数 ...

最新文章

  1. 第11章 UART 串口通信(手把手教你学51单片机pdf部分)
  2. 解锁oracle数据库的 scott用户,亲身测试。success
  3. flat在java中的含义_java – 在flatingBy中使用flatMap的优雅方法
  4. 华为高密UA5000升级
  5. C++知识点52——多重继承
  6. 第10章 序列的修改、散列和切片
  7. 数字图像处理实验(3):PROJECT 02-03, Zooming and Shrinking Images by Pixel Replication
  8. 【数据结构链表】之五单链表
  9. B-树、B+树、B*树详解
  10. php curl_error源码,PHP curl_error函数
  11. Oracle 数据库监听配置
  12. SQL --几张表公有字段的查询
  13. 自学前端两三个月,很迷茫,有大佬可以指导吗?
  14. uni-app目录结构介绍
  15. python (集合和深浅拷贝)
  16. Android Measure测量实际应用心得(一)
  17. jspsmartupload简述
  18. 计算机单位mb和m大小一样吗,MB和M哪个容量大?
  19. 计算机组成原理语言方框图,计算机组成原理3---方框图语言
  20. CSS层叠样式表Cascading Style Sheets(2021.10.05)

热门文章

  1. linux文件系统dentry_文件系统中超级块、inode和dentry三者的分析
  2. 在Word里面,简单制作文档目录
  3. 八、IMU器件温度漂移补偿
  4. 西门子PLC300编程实例程序70例 含RFID读写器专用功能块 西门子PLC300编程应用实例程序
  5. 手机web页面PC浏览器打开有滚动条,手机浏览器打开没有
  6. ABBYY FineReader16最新PDF图片文字识别软件
  7. Worthington 胰蛋白酶抑制剂解决方案
  8. C语言I———作业06
  9. 投放无忧!教育、家装、婚摄、旅游等8大热门行业广告投放攻略
  10. CPU中的一级缓存,二级缓存,三级缓存