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.)

5
  • 2
    @Arup Rakshit: Needs quoting on those strings. Commented Sep 25, 2013 at 9:34
  • 1
    @Victor: Which Ruby library are you using for SQL access? It is easier to answer you if that is known. Commented Sep 25, 2013 at 9:37
  • @NeilSlater Using MySQL and Ruby 1.9. Commented Sep 25, 2013 at 10:14
  • Thanks. I mean what gem; what class is con in your question? Commented Sep 25, 2013 at 10:20
  • mysql gem. con = Mysql.new 'localhost', 'root', '', 'data' Commented Sep 25, 2013 at 10:24

2 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

+1 for the suggestion to use a sanitizer. SQL injection is amusing until it happens to you.
I always have that problem. lol. What sanitizer would you suggest?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.