Ruby 和 mysql2:循环直到连接无错误
Ruby and mysql2: Looping Until Connection is Error Free
Context:我正在 Ruby 中使用 mysql2
gem.
编写一个简单的动态查询
尝试:
#!/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)
mysql2
gem 定义了 Mysql2::Error
,而不是`Mysql2::StandardError.
你需要营救Mysql2::Error
有关详细信息,请参阅 mysql2 Github source。
Context:我正在 Ruby 中使用 mysql2
gem.
尝试:
#!/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)
mysql2
gem 定义了 Mysql2::Error
,而不是`Mysql2::StandardError.
你需要营救Mysql2::Error
有关详细信息,请参阅 mysql2 Github source。