0

Hi Im using Ruby as a scripting language. Not for web development, but to connect to a local database on my computer and manipulate it.

Id like to know how I can connect. Do I need to download/import tools? What do I need to get started?

Thanks,


Update

I did gem install mysql2 and ran the following ruby file

require 'mysql2'  

#my = Mysql.new(hostname, username, password, databasename)  
con = Mysql.new('localhost', 'nverma', 'something', 'ruby')  
rs = con.query('select * from contacts')  
rs.each_hash { |h| puts h['name']}  
con.close

and got the following error:-

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext
 /kernel_require.rb:55:in `require': dlopen(/Library/Ruby/Gems/2.0.0/gems/mysql2-0.3.16/lib/mysql2 
 /mysql2.bundle, 9): Library not loaded: libmysqlclient.18.dylib (LoadError)
 Referenced from: /Library/Ruby/Gems/2.0.0/gems/mysql2-0.3.16/lib/mysql2/mysql2.bundle
 Reason: image not found - /Library/Ruby/Gems/2.0.0/gems/mysql2-0.3.16/lib/mysql2/mysql2.bundle
 from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext 
 /kernel_require.rb:55:in `require'
 from /Library/Ruby/Gems/2.0.0/gems/mysql2-0.3.16/lib/mysql2.rb:8:in `<top (required)>'
 from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext
 /kernel_require.rb:135:in `require'
 from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext
 /kernel_require.rb:135:in `rescue in require'
 from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext
 /kernel_require.rb:144:in `require'
 from sol5.rb:1:in `<main>'

Please help!

2
  • Look at the mysql2 gem. Commented Jul 31, 2014 at 5:08
  • Please have a look on the updated question! Commented Jul 31, 2014 at 5:42

2 Answers 2

3

One option is to use the mysql2 gem:

gem install mysql2

Connect to your database:

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

Query the database:

results = client.query("SELECT * FROM users")
Sign up to request clarification or add additional context in comments.

Comments

0

Looking at your update, is the Mysql class your own class? If so can you post that code also?

If not and you are trying to use mysql2 directly here, then you need instantiate the db connection the way @infused said in the other answer:

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.