首页 > 解决方案 > 如何处理 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

标签: rubytypessqlite

解决方案


您实际上不必计算所有匹配的行,也不必查看获取的行的内容:

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

推荐阅读