【问题标题】:Ruby DBI - How to check if a recordset is emptyRuby DBI - 如何检查记录集是否为空
【发布时间】:2011-11-22 14:33:50
【问题描述】:

使用 Ruby DBI,我如何检查记录集是否为空? (无需遍历它或进行计数查询)

sth = dbh.prepare("select * from things WHERE created_at > '#{start}'")
sth.execute

【问题讨论】:

    标签: ruby dbi


    【解决方案1】:

    你总是可以只问结果对象:

    res = sth.execute
    res.num_rows
    

    不过,该操作必须拉下所有匹配的记录,因此如果您只需要计数,您可能需要直接选择它。

    转义您的 SQL。您不能只在其中放置任意字符串。这样更好:

    sth = dbh.prepare("select * from things WHERE created_at > '%s'" % sth.escape_string(start))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 2018-12-23
      • 2021-06-01
      • 1970-01-01
      相关资源
      最近更新 更多