FuzedBulb
FuzedBulb

Reputation:

How to escape string in Ruby to protect against SQL Injection? (No Rails)

I just wanted to know how can we escape an SQL query (string) in Ruby to prevent SQL Injection. please note I am not using Rails framework.

Thanks.

Upvotes: 14

Views: 17475

Answers (4)

Andy Lester
Andy Lester

Reputation: 93636

Don't try to sanitize your data. Use prepared statements. See also http://bobby-tables.com/ruby.html

Upvotes: 0

ice cream
ice cream

Reputation: 2470

Write a wee function to quote strings. I think Rails just uses something like this:

def quote_string(v)
  v.to_s.gsub(/\\/, '\&\&').gsub(/'/, "''")
end

Upvotes: 3

greyfade
greyfade

Reputation: 25647

If possible, use the Ruby DBI module, and instead of trying to quote your strings, use parametrized prepared queries, like this:

dbh = DBI.connect("DBI:Mysql:test:localhost", "testuser", "testpass")
sth = dbh.prepare("INSERT INTO people (id, name, height) VALUES(?, ?, ?)")
File.open("people.txt", "r") do |f|
  f.each_line do |line|
    name, height = line.chomp.split("\t")
    sth.execute(nil, name, height)
  end
end

Quoting will be handled properly for you, and injections will be a thing of the past.

Edit: Note that this example shows nil being passed as the first parameter to execute(). It corresponds to the first ? in the query, and is translated to "NULL" by the DBI module. The other parameters are similarly properly quoted and inserted into the query.

Upvotes: 17

Ryan Bigg
Ryan Bigg

Reputation: 107718

You don't have to use rails, you could just require 'activerecord' and use it as you would in rails (define models and use those). What you're doing there is just re-inventing the wheel.

Upvotes: 2

Related Questions