Handling ExecuteScalar() when no results are returned

后端 未结 22 1148
猫巷女王i
猫巷女王i 2020-11-27 05:47

I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:

sql = \"select username from usermst wh         


        
22条回答
  •  醉酒成梦
    2020-11-27 06:21

    First you should ensure that your command object is not null. Then you should set the CommandText property of the command to your sql query. Finally you should store the return value in an object variable and check if it is null before using it:

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

    I'm not sure about the VB syntax but you get the idea.

提交回复
热议问题