2016-03-01 40 views
0

上下文:我正在使用mysql2 gem編寫一個簡單的Ruby動態查詢。Ruby和mysql2:循環直到連接無錯誤

嘗試:

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

與工作寶石。

最後,在終端中輸入錯誤:答案後

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

mysql2寶石定義Mysql2::Error,不`Mysql2 :: StandardError的。

您需要搶救Mysql2::Error

參考mysql2 Github source獲取更多信息。

+0

現在我收到的錯誤: '無法通過套接字「/tmp/mysql.sock」連接到本地MySQL服務器(2)2002' 一遍又一遍,而不能'按Ctrl + C' 。 – EVAL

+1

這是一個完全不同的問題。基本上'mysql2'無法連接到MySQL服務器。當你正在救援和重試時,你會一遍又一遍地看到錯誤。 – Dharam

+0

我收集到我無法連接。我應該改述:我想知道爲什麼我無法再次執行下面的代碼:'puts「錯誤:請重試。」 放入「輸入主機,用戶名,密碼和數據庫:」 hst = gets.chomp! user = gets.chomp! pass = gets.chomp! '重試'後db = gets.chomp!'。 – EVAL