Ruby MySQL DBI example

No real introduction here today, just some sample Ruby code I want to have out here so I can remember some syntax for using Ruby to connect to a MySQL database.

In particular I am also using the here document syntax to simplify the writing and reading of a long database query.

Ruby MySQL DBI example

# require the dbi driver
require 'dbi'

# here is my long sample query
query = <= '2006-07-01'
and status = 1
and project like 'Quarry%'
and employee_full_name in ('Fred Flinstone', 'Barney Rubble', 'Wilma%')
order by name, date, project;
FOO
# mysql connect statement
dbh = DBI.connect('DBI:Mysql:the_database:localhost', 'root', 'the_password')
sth = dbh.prepare(query)
sth.execute

# print each database row
while row=sth.fetch do
p row
end

sth.finish
dbh.disconnect