Error connecting to Mysql

I am having trouble connecting to mysql database. I’m i missing something? This is my database connection file:

require "mysql2"

# error trap
begin
  dbh = Mysql2::new('127.0.0.1','root','','Accounts')
rescue Exception => e
  puts "Unable to connect to database. Error: \\"#{e}\\""
  exit 1
end

Error thrown:

Unable to connect to database. Error: "undefined method `new' for Mysql2:Module"

What’s the best way to connect to mysql database in ruby… not rails… im working on com-line app?

Have a look at the usage for that gem here.


client = Mysql2::Client.new(:host => "localhost", :username => "root")

Yh had a look at it… looks very cool and neat - definitely way to go. And also found another way of doing it in case someone wants to experiment with other ways: http://ruby-dbi.rubyforge.org/rdoc/files/README.html

Thanks again.

just had to post this:


# require necessary libs
require "rubygems"
require "mysql2"

# error trap: exception handler
begin
  @dbh = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "", :database => "dbname")
rescue Exception => e
  puts "Unable to connect to database. Error: \\"#{e}\\""
  exit 1
end

works just fine … Thank you so much @markbrown4, You’re the man!

No problemo. Happy to help :slight_smile:

Just curious… does this method also support prepared statements?

I use Rails exclusively so am only familiar with the things that ActiveRecord supports, so I had to go look up what prepared statements were :wink:

Yes, the mysql2 module appears to support them.