Handling ExecuteScalar() when no results are returned

后端 未结 22 996
猫巷女王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:06

    this could help .. example::

    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();
      }
    }
    

    from this here

    0 讨论(0)
  • 2020-11-27 06:06
    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();
            }
    
        }
    
    0 讨论(0)
  • 2020-11-27 06:08

    Try this

    sql = "select username from usermst where userid=2"
    
    string getusername = Convert.ToString(command.ExecuteScalar());
    
    0 讨论(0)
  • 2020-11-27 06:09

    I'm using Oracle. If your sql returns numeric value, which is int, you need to use Convert.ToInt32(object). Here is the example below:

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 06:10

    I had this issue when the user connecting to the database had CONNECT permissions, but no permissions to read from the database. In my case, I could not even do something like this:

    object userNameObj = command.ExecuteScalar()

    Putting this in a try/catch (which you should probably be doing anyway) was the only way I could see to handle the insufficient permission issue.

    0 讨论(0)
  • 2020-11-27 06:11

    In your case either the record doesn't exist with the userid=2 or it may contain a null value in first column, because if no value is found for the query result used in SQL command, ExecuteScalar() returns null.

    0 讨论(0)
提交回复
热议问题