Hi there, I have been happily playing with RoR on my windows machine and
using it with Mysql. But today I tried to write a stand-alone script
that connects to mysql to do some housekeeping and I can not get a
connection. I tried “require ‘mysql’” first but that didn’t work so I
searched through the Ruby dir and found a reference to DBI/DBH so going
with an example online I tried “require ‘dbi’” but that also fails with
"…in ‘load_driver’: is not a class/module (TypeError).
What does RoR use to connect to mysql? Can’t I just use the same
library?
After you install the Ruby and MySQL you must install Ruby’s MySQL
interface. Then you can load it in your script to connect to the
database. To make the connection you must provide the host, username
and password.
require ‘mysql’
db_con = Mysql.new(“localhost”, “ruby”, “password”, “mydb”)
result = db_con.query(“Select * from MyTable”)
result.each_hash do |r|
print “#{r[‘column1’]}”
end
Read the README file to see what classes are available. Check out the
online documentation for interacting with the database.
Rails needs the MySQL driver installed on the machine. It also
requires the connection parameters to be specified in the database.yml
file. I don’t know if you can use the Rails framework classes for
connecting to the database.
Rails Recipe book has a recipe “Use Active Record Outside of Rails”
For simple scripts you can use the ActiveRecord::Base class to
establish a database connection, then you just make your class extend
from it. Now all the methods of the ActiveRecord is available to you.
Refer the online documentation of Rails for the syntax and usage.
Thanks guys, I just assumed that if RoR was installed and working with
mysql already I could just load up the lib and play. I don’t want to
use ActiveRecord as these are just housekeeping scripts and I need them
to be as fast as possible.