【问题标题】:How to use Sequel to select one field from database如何使用 Sequel 从数据库中选择一个字段
【发布时间】:2013-06-07 00:32:24
【问题描述】:

我将 Sinatra 和 Sequel 与 PostgreSQL 一起使用。

身份验证后,我想通过打印用户名来欢迎用户,但我不能只从数据库中获取用户名的值,它以哈希的形式出现。

查询是:

current_user = DB[:users].select(:username).where('password = ?', password).first

得到的数据是:

Welcome, {:username=>"Rich"}

这看起来很奇怪,我更喜欢读“Welcome, Rich”。

我在这里做错了什么?我尝试了相同的查询,最后没有“第一”,这也不起作用。

【问题讨论】:

  • 我认为你应该使用current_user[:username]
  • 感谢您的建议。已解决:DB['select username from users where email_address = ?', email_address].each do |row| current_user = row[:username] ..... end 就像 PHP。大声笑!
  • 当然! current_user[:username] 也可以。你看我是 ruby​​ 和 ORM 风格数据库交互的新手,所以这对我来说有点神秘。无论如何,干杯!
  • 不要写像DB["some query"]这样的查询。当你这样做时,你会错过 Sequel 和 ORM 的强大功能。阅读Sequel cheat sheet,快速了解它应该如何使用。

标签: ruby postgresql sinatra sequel


【解决方案1】:

您可以从给定的哈希中提取您选择的(单个)列:

current_user = DB[:users].select(:username).where('password=?', password).first[:username]

或者您可以map your results 到一组用户名并拉出第一个:

# Using a hash in the filter method is simpler than SQL placeholders.
current_user = DB[:users].filter(password:password).select_map(:username).first

但最好的方法是先获取only the user you care about,然后获取名称:

# Using [] on a dataset returns the first row matching the criteria
current_user = DB[:users][password:password][:username]

【讨论】:

    【解决方案2】:

    尝试 Sequel::Dataset#get。此外,正如 Phrogz 所指出的,Sequel::Dataset#where 可以采用散列(它将安全地转义值以防止注入攻击)。

    current_username = DB[:users].where(password: password).get(:username)
    

    还有 Sequel::Dataset#where_single_value,针对这种情况进行了优化:

    current_username = DB[:users].select(:username).where_single_value(password: password)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 2016-06-14
      相关资源
      最近更新 更多