如何使用 Sequel 运行原始 SQL 查询 [英] How to run raw SQL queries with Sequel

查看:40
本文介绍了如何使用 Sequel 运行原始 SQL 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还不清楚使用 Sequel 运行原始 SQL 查询的正确方法.

I am not clear yet on the proper way to run raw SQL queries with Sequel.

目前我正在尝试这个:

DB.fetch("SELECT * FROM zone WHERE dialcode = '#{@dialcode}' LIMIT 1") do |row|
 @zonename = row
end

如何将查询作为原始 SQL 运行,然后像平常一样访问结果?

How can I can run the queries as raw SQL then access the results like normal?

if @zonename.name = "UK"

推荐答案

我有一些可能有用的提示:

I have a few pointers which may be useful:

  1. 你可以简单地:

  1. You could simply do:

@zonename = DB.fetch("SELECT * FROM zone WHERE dialcode = ? LIMIT 1", @dialcode).first

注意:您忽略了可能有更多符合条件的结果这一事实.如果您希望返回多个可能的行,那么您可能希望通过执行 ...

NB: you are ignoring the fact that there could be more results matching the criteria. If you expect multiple possible rows to be returned then you probably want to build an array of results by doing ...

@zonename = DB.fetch("SELECT * FROM zone WHERE dialcode = ? LIMIT 1", @dialcode).all

并处理所有这些.

返回集是一个散列.如果 @zonename 指向其中一条记录,则您可以执行

The return set is a hash. If @zonename points to one of the records then you can do

@zonename[:column_name] 

引用名为column_name"的字段.你不能做 @zonename.colum_nname(你实际上可以使用一些元编程用辅助方法装饰 @zonename,但我们暂时忽略它).

to refer to a field called "column_name". You can't do @zonename.colum_nname (you could actually decorate @zonename with helper methods using some meta-programming but let's ignore that for the moment).

Sequel 是一个出色的界面,您对它了解得越多,您就会越喜欢它.

Sequel is an excellent interface, the more you learn about it the more you'll like it.

这篇关于如何使用 Sequel 运行原始 SQL 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆