Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run raw SQL queries with Sequel

Tags:

sql

ruby

sequel

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"
like image 545
veccy Avatar asked Jun 29 '10 21:06

veccy


People also ask

Can I run 2 SQL queries at once?

You can include multiple SQL statements on the SQL query panel. The exceptions are CALL and CREATE PROCEDURE statements. These statements must be used alone in a query.

How do I get raw query in Sequelize?

As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the sequelize. query method. By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc).

How do I run a SQL query on another query?

Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY.


2 Answers

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.

like image 153
Jeremy Evans Avatar answered Oct 02 '22 17:10

Jeremy Evans


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.

  1. 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.column_name (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.

like image 15
Chris McCauley Avatar answered Oct 02 '22 16:10

Chris McCauley