tags:

views:

64

answers:

1

I need to use Ruby to create some SQL statements for a MySQL database. Ruby will never connect to the database. The SQL statements will be sent to another site and executed against the MySQL database.

Since the machine running Ruby does not have a connection to the database, is it possible to use DBI's prepare statement without creating a handle to the MySQL database?

+1  A: 

ruby-dbi does include an emulator for preparing statements when the dbd does not provide it. You can use it as follows:

require 'dbi'
st = DBI::SQL::PreparedStatement.new(nil, "Select * from table where x = ?")
st.bind(['test']) # => "Select * from table where x = test"

You can see the algorithm it uses here.

Edit: Based on the comments below a, dbi 0.2.2 version

require 'dbi'
class Quoter ; include DBI::SQL::BasicQuote ; end
st = DBI::SQL::PreparedStatement.new(Quoter.new, "Select * from table where x = ?")
st.bind(['test']) # => "Select * from table where x = 'test'"

Relevant source file is here.

anshul
The code above produces an error. It seems that a quoter class is needed. --> NoMethodError: undefined method `quote' for nil:NilClass from C:/Ruby/lib/ruby/site_ruby/1.8/dbi/sql.rb:198:in `bind' from C:/Ruby/lib/ruby/site_ruby/1.8/dbi/sql.rb:197:in `each' from C:/Ruby/lib/ruby/site_ruby/1.8/dbi/sql.rb:197:in `bind' from (irb):15
sutch
Works like a charm in Ruby 1.9.1/ dbi 0.4.3. What version of dbi/ruby are you on? We could probably find the corresponding code for that version.
anshul
I'm using Ruby 1.8.6 / dbi 0.2.2.
sutch
This should work... On a side note, you are on a Jurassic platform. Do consider upgrading.
anshul