sqlite3 gem的#execute和#query方法的返回值 [英] Return Values of #execute and #query methods of sqlite3 gem
问题描述
我正在sqlite3 gem的帮助下在ruby中使用sqlite3数据库(我试图在不使用ActiveRecords的情况下更好地了解使用sqlite3 gem).我在下面有一个SQL查询:
I am working with sqlite3 database in ruby with the help of sqlite3 gem (I'm trying to gain a better understanding of using sqlite3 gem without the use of ActiveRecords). I have an sql query below:
SELECT id FROM contacts WHERE first_name = 'Charles'
我希望它从中返回值'5'
From which I'm expecting it to return the value '5'
$db.execute('SELECT id FROM contacts WHERE first_name = ?', 'Charles') do |result|
puts result
end
以上将打印"5",但将返回一个sqlite3对象.我似乎无法获得execute
方法来返回值"5".
Above will print '5', but will return an sqlite3 object. I couldn't seem to get the execute
method to return the value '5'.
$db.query('SELECT id FROM contacts WHERE first_name = ?', 'Charles') do |result|
result.first.first
end
我能得到的最接近的方法是使用query
方法返回值"5"(见上),但这需要.first.first
似乎很复杂.
The closest I could get is to use the query
method to return the value '5' (above), but this requires .first.first
which seems convoluted.
我是否有更好的方法来获得所需的价值?即可能通过访问sqlite3对象?
Is there a better way for me to get the value I needed? i.e. perhaps through accessing the sqlite3 object?
推荐答案
尝试这个
$db.results_as_hash = true
$db.execute('SELECT id FROM contacts WHERE first_name = ?', 'Charles') do |row|
puts row['id']
end
您需要一种方法.做类似的东西
You want a method. Make something like
def find_id_by_first_name(first_name)
$db.results_as_hash = true
$db.execute('SELECT id FROM contacts WHERE first_name = ?', first_name) do |row|
return row['id']
end
end
但是无论如何,您的查询可能有问题.如果first_name
没有唯一索引,则此查询可能返回多个行.因此,这种方法没有太大意义.这只会返回第一个匹配结果.
But anyway, you could have a problem with your query. If first_name
has not a unique index, this query could return more than one row. So this method doesn't make so much sense. This just returns the first matching result.
这篇关于sqlite3 gem的#execute和#query方法的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!