【发布时间】:2016-03-01 20:20:49
【问题描述】:
上下文:我正在使用 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)
【问题讨论】:
标签: mysql ruby loops mysql2 rescue