1

Using MySQL and Ruby 1.9. I have the following hash:

h = {:country=>"Thailand", :postal_code=>"10110"}

and I wish to run this SQL statement:

con.query "UPDATE table SET country = 'Thailand', postal_code = '10110' WHERE id = 1;"

I have tried several methods, but couldn't seem to construct the desired statement. How should I do that?

(Please ignore the ID and postal code integer, doesn't matter for now.)

4

2 回答 2

3

I'll recommend you look at using the Sequel ORM. It makes it very easy to work with databases like MySQL, PostgreSQL, Oracle, SQLite, MSSQL, etc., using a single code base.

If you want to develop using SQLite, test using MySQL or PostgreSQL and run in production using Oracle, you can do it without changing any code, only your DSN in a single string changes when you make your connection.

It writes very clean SQL, allows you to use custom queries easily if you want. We use it for all our Ruby database connectivity and love it.

You can use a hash exactly like yours to generate queries right out of the box. This is from the documentation:

Filtering Records

An easy way to filter records is to provide a hash of values to match to where:

my_posts = posts.where(:category => 'ruby', :author => 'david')
# WHERE category = 'ruby' AND author = 'david'

See the README for more examples.

于 2013-09-25T10:43:49.640 回答
2

You mean something like this ?

h = {:country => "Thailand", :postal_code => "10110"}
"UPDATE table SET #{h.map { |k, v| "#{k} = '#{v}'" }.join(', ')} WHERE id = 1;"
# "UPDATE table SET country = 'Thailand', postal_code = '10110' WHERE id = 1;"

But you would better use a sanitizer instead of simple single quotes.

于 2013-09-25T09:35:34.657 回答