How to run raw SQL queries with Sequel

让人想犯罪 __ 提交于 2019-11-27 02:47:25

问题


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

Currently I am trying this:

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

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

if @zonename.name = "UK"

回答1:


I have a few pointers which may be useful:

  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
    

    and processing all of them.

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

    @zonename[:column_name] 
    

    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 is an excellent interface, the more you learn about it the more you'll like it.




回答2:


Note that instead of:

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

you should do:

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

Otherwise, you open yourself to SQL injection if you don't control the contents of @dialcode.



来源:https://stackoverflow.com/questions/3144813/how-to-run-raw-sql-queries-with-sequel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!