Search code examples
mysqlrubyloopsmysql2rescue

Ruby and mysql2: Looping Until Connection is Error Free


Context: I am writing a simple dynamic query in Ruby using the mysql2 gem.

Attempt:

#!/usr/local/bin/ruby
require "mysql2"

puts "Please enter the title of this Report:"
title = gets.chomp

Mysql2::Client.default_query_options.merge!(:as => :array)

puts "Please enter the host, username, password and database in order:"
hst = gets.chomp
user = gets.chomp
pass = gets.chomp
db = gets.chomp

begin
  mysql = Mysql2::Client.new(:host => hst, :username => user, :password => pass, :database => db)
rescue Mysql2::Error => e
    puts e.errno
    puts e.error
  retry
  puts "Error: please try again."
  puts "Enter the host, username, password and database:"
  hst = gets.chomp!
  user = gets.chomp!
  pass = gets.chomp!
  db = gets.chomp!
end

puts "Successfully accessed #{db}!"

Note that:

rescue Mysql2::Error => e
    puts e.errno
    puts e.error

works with the mysql gem, but:

rescue Mysql2::StandardError => e
    puts e.errno
    puts e.error

does not work with the mysql2 gem.

Finally, the error in Terminal:

iMac:workspace guy$ ruby File.rb
Please enter the title of this Report:
title
Please enter the host, username, password and database in order:
1.2.3.4
username15
password123
db_one
File.rb:19:in `rescue in <main>': uninitialized constant Mysql2::StandardError (NameError)
Did you mean?  StandardError
    from File.rb:17:in `<main>'

Edit after answer: leaving :host as :hst gave me the following error:

2002
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Solution

  • mysql2 gem has defined Mysql2::Error, not `Mysql2::StandardError.

    You need to rescue Mysql2::Error

    Refer to mysql2 Github source for more info.