Handling ExecuteScalar() when no results are returned

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

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

提交回复
热议问题