Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, MySQL2: check if the result is empty

Tags:

mysql

ruby

mysql2

I am using MySQL2 in Ruby to query a database. What is a direct way to check whether the result of a query is empty? The code looks like:

require 'mysql2'
client = Mysql2::Client.new(:host => "localhost", :username => "root")
results = client.query("SELECT * FROM users WHERE group='githubbers'")
like image 533
Marco Avatar asked Dec 08 '22 14:12

Marco


2 Answers

The Mysql2 documentation is indeed very poor. But by inspecting the type of results you will notice that it is a Mysql2::Result which contains 3 methods. The one that you are interested in is count (or alias size) which will return the number of rows of the result.

From here you can easily check if it is 0:

(results.count == 0)

Alternatively you could open the Mysql2::Result class and add the method empty? yourself:

class Mysql2::Result
    def empty?
        (count == 0)
    end
end

And then you can just do:

results.empty?
like image 98
Shoe Avatar answered Dec 11 '22 09:12

Shoe


0 == results.size

will return true if results is empty. AFAIK there is no direct method (such as Array#empty?) , but you could monkey patch it.

like image 21
nTraum Avatar answered Dec 11 '22 07:12

nTraum