[英]Ruby, MySQL2: check if the result is empty
I am using MySQL2 in Ruby to query a database. 我在Ruby中使用MySQL2来查询数据库。 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'")
The Mysql2
documentation is indeed very poor. Mysql2
文档确实很差。 But by inspecting the type of results
you will notice that it is a Mysql2::Result
which contains 3 methods. 但是通过检查results
的类型,您会注意到它是一个包含3种方法的Mysql2::Result
。 The one that you are interested in is count
(or alias size
) which will return the number of rows of the result. 您感兴趣的是count
(或别名size
),它将返回结果的行数。
From here you can easily check if it is 0
: 从这里您可以轻松检查它是否为0
:
(results.count == 0)
Alternatively you could open the Mysql2::Result
class and add the method empty?
或者你可以打开Mysql2::Result
类并将方法添加为empty?
yourself: 自己:
class Mysql2::Result
def empty?
(count == 0)
end
end
And then you can just do: 然后你可以这样做:
results.empty?
0 == results.size
will return true
if results
is empty. 如果results
为空,则返回true
。 AFAIK there is no direct method (such as Array#empty?
) , but you could monkey patch it. AFAIK没有直接的方法(例如Array#empty?
),但你可以修补它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.