ruby - 如何处理 ruby 中的 sqlite 查询的结果?
问题描述
我面前有一个简单的任务,通过 ruby 的 sqlite3 库查询数据库中是否存在某行。下面找到我的尝试。
必须有比下面更好(不那么冗长)的方法。它是什么?Ruby 的“Enumerable”类有什么我应该看的吗?一般如何确定sql结果的数据类型?
#!/usr/bin/env ruby
require 'sqlite3'
db = SQLite3::Database.open "example.db"
db.execute "create table if not exists example (id INTEGER PRIMARY KEY, words TEXT, whence DATETIME, number INT)"
words = "words"
begin
insert = db.prepare "insert into example (words,whence,number) values (?,?,?)"
insert.bind_param 1, words
insert.bind_param 2, Time.now.to_s
insert.bind_param 3, 42
insert.execute
rescue SQLite3::Exception => e
puts "Problem with insert"
puts e
end
begin
query = db.prepare "select count(*) as count from example where words = ?"
query.bind_param 1, words
rs = query.execute
#puts rs.first
res = rs.first.to_a
puts res
#if (rs.first.to_s.to_i > 0)
if (res.first.to_i > 0)
puts "rs.first greater than 0"
else
puts "it won't get here."
end
#if (rs.first == nil
# puts "result is nil"
#else
# puts "result is NOT nil"
#end
rescue SQLite3::Exception => e
puts "Problem with query"
puts e
end
解决方案
您实际上不必计算所有匹配的行,也不必查看获取的行的内容:
query = db.prepare "select 1 from example where words = ?"
query.bind_param 1, words
if query.execute.next
puts "found."
else
puts "it won't get here."
end
推荐阅读
- javascript - 更新 redux 存储中数组中的嵌套对象
- reactjs - 将“类”转换为“反应钩子”
- googledns - 如何将 TXT 记录添加到区域以证明所有权
- javascript - 使用 pdf.js 将 PDF 渲染为 PNG 时出现“无效的画布大小”
- github - 关于推送从 FTP 到 git repo 的代码更改
- .htaccess - .htaccess 重定向——两个重定向之间的区别
- python - 用运算求解代数方程
- python - 有没有更有效的方法将多行字符串转换为 numpy 数组?
- java - 如何使用相关表中的数据更新关系表的字段
- google-apps-script - GoogleAppsScript中要求客户将问题回复给Linebot的功能后如何触发线路通知功能?