How to run raw SQL queries with Sequel

前端 未结 2 384
再見小時候
再見小時候 2020-12-09 17:30

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 = \         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 18:23

    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.

提交回复
热议问题