【问题标题】:Ruby and mysql2: Looping Until Connection is Error FreeRuby 和 mysql2:循环直到连接无错误
【发布时间】: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


    【解决方案1】:

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

    你需要拯救Mysql2::Error

    请参阅mysql2 Github source 了解更多信息。

    【讨论】:

    • 现在我收到错误:Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) 2002 一遍又一遍地无法Ctrl + C
    • 那是一个完全不同的问题。基本上mysql2 无法连接到 MySQL 服务器。当您进行救援和重试时,您会一遍又一遍地看到错误。
    • 我知道我无法连接。我应该改写一下:我想知道为什么我无法再次执行以下代码: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! after retry.
    • 一旦执行到retry,它就会跳转到begin,并且永远不会到达retry之后的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2021-03-20
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多