Ruby和mysql2:循环直到连接没有错误

时间:2016-03-01 20:20:49

标签: mysql ruby loops mysql2 rescue

Context :我正在使用mysql2 gem在Ruby中编写一个简单的动态查询。

尝试:

#!/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}!"

注意

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

适用于mysql gem,但是:

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

使用mysql2 gem。

最后,终端中的错误:

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>'

回答后修改:将:host留给:hst给了我以下错误:

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

1 个答案:

答案 0 :(得分:1)

mysql2 gem定义了Mysql2::Error,而不是`Mysql2 :: StandardError。

您需要解救Mysql2::Error

有关详细信息,请参阅mysql2 Github source