0
#!/usr/bin/ruby -w
require "rubygems"
require "mysql"
begin
     # connect to the MySQL server
     dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", 
                        "nyros", "root")
     # get server version string and display it
     row = dbh.select_one("SELECT VERSION()")
     puts "Server version: " + row[0]
rescue DBI::DatabaseError => e
     puts "An error occurred"
     puts "Error code:    #{e.err}"
     puts "Error message: #{e.errstr}"
ensure
     # disconnect from server
     dbh.disconnect if dbh
end

I want to connect and access MySQL database through ruby programming. But i am getting this error when executing the ruby code in my terminal.

Error:

/.rvm/rubies/ruby-1.9.3 p547/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:55:in 'require': cannot load such file -- mysql (LoadError)
from /home/nyros/.rvm/rubies/ruby-1.9.3-p547/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:55:in 'require'
from task.rb:3:in '<main>'

1 Answer 1

1

I suggest using mysql2. It is a mysql library for Ruby.

For example:

require 'mysql2'

client = Mysql2::Client.new(:host => HOST, :username => USERNAME, :database => DATABASE)
client.query("select * from tabel_name;")

If you don't want to use mysql2, you also can refer to this link.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.