I am starting to learn ruby and am working on a test script to import some data into a MySQL database. I am using the below code found on kitebird.com to first get the MySQL connection from Ruby working. The code was producing an error which I figured might be because I installed the MySQL Ruby gem instead of installing the MySQL Ruby module from source.
The below code attempts to connect to the MySQL server to return the MySQL server version.
Code:
- require 'mysql'
- begin
- # connect to the MySQL server
- dbh = Mysql.real_connect("localhost", "user", "password", "database")
- # get server version string and display it
- puts "Server version: " + dbh.get_server_info
- rescue Mysql::Error => e
- puts "Error code: #{e.errno}"
- puts "Error message: #{e.error}"
- puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
- ensure
- # disconnect from server
- dbh.close if dbh
- end
Running this code with the MySQL gem installed returned the below error.
Error:
- test.rb:1:in `require': no such file to load -- mysql (LoadError)
- from test.rb:2
This was telling me it was having trouble loading the mysql module so I figured out that the rubygems gem must be loaded first. The below code only adds one line to the beginning of the script to make things work properly.
- require 'rubygems'
- require 'mysql'
- begin
- # connect to the MySQL server
- dbh = Mysql.real_connect("localhost", "user", "password", "database")
- # get server version string and display it
- puts "Server version: " + dbh.get_server_info
- rescue Mysql::Error => e
- puts "Error code: #{e.errno}"
- puts "Error message: #{e.error}"
- puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
- ensure
- # disconnect from server
- dbh.close if dbh
- end
Now when running this code I get the following result.
- [user@server ~]$ ruby test.rb
- Server version: 5.0.45
Obviously this is now returning the MySQL server version which on the server the script is being run on happens to be 5.0.45.
I just started on ruby, this was a gr8 help thanks.
Hello Wael,
Glad the article helped you out. Ruby is awesome! Thanks for taking the time to leave feedback.
Thanks.
alex
thx a lot
I am also facing the same problem.
but now its solved.
Hello manish,
No problem. Glad to hear your problem was resolved by the information provided in the article above.
Thanks.
alex