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



上下文:我正在使用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宝石,但:

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

不适用于mysql2宝石。

最后,终端中的错误:

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)
mysql2 gem定义了

Mysql2::Error,而不是'Mysql2::StandardError。

你需要拯救Mysql2::Error

请参阅 mysql2 Github 源代码以获取更多信息。

最新更新