2012-02-27 24 views
2

我有一個使用ActiveRecord(2.3.12)訪問MySQL數據庫的ruby腳本。流程類似於「從配置文件讀取數據庫值」,「連接到數據庫」,「創建表A如果它不存在」,「下載並解析文件」,「將解析的記錄保存到A」。ActiveRecord實際連接到數據庫的哪一點?

的代碼如下所示:

ActiveRecord::Base.establish_connection(
    :adapter => 'mysql', 
    :database => database_name, 
    :username => username, 
    :password => password, 
    :host => "localhost", 
    :port => 3306 
) 

    ... 

ActiveRecord::Schema.define do 
    create_table a, :force => true do |t| 
    t.string :last_name, :limit => 60, :default => "", :null => false 
    t.string :first_name, :limit => 30, :default => "", :null => false 
    t.string :middle_initial, :limit => 2, :default => "" 
    t.string :dob, :limit => 12, :default => "", :null => false 
    end 
end unless A.table_exists? 

但是,如果我把不正確數據庫憑據,或者一個不存在的數據庫名稱爲establish_connection方法,劇本似乎並沒有給出任何錯誤或拋出任何異常,直到我實際嘗試對數據庫執行一些操作(即創建表A)。我嘗試了begin-rescue-endestablish_connection,但它從未進入rescue塊。

爲什麼establish_connection似乎不是真的......好......建立連接?而對於我的生活,我無法弄清它甚至應該返回什麼。文檔HERE當然似乎沒有任何幫助。

或者我做錯了什麼?請幫忙!

回答

3

我通常使用ActiveRecord::Base.connection.active?語句來檢查ActiveRecord是否真的連接到數據庫。

def establish_database_connection 
    begin 
    ActiveRecord::Base.establish_connection config["database"] 
    ActiveRecord::Base.connection.active? 
    logger.info "Connected to Database" 
    rescue Exception => e 
    logger.error "Exception db connection : #{e.message} " 
    raise "Database connection failed" 
    end 
end 

沒有ActiveRecord :: Base.connection.active?聲明上面的代碼不會引起無效憑證上的任何錯誤。

0

我不是專家,但我始終認爲establish_connection更多的是一個連接定義的,而在使用時的實際連接時,在這種情況下,當table_exists?運行

2

RSK的解決方案將爲當前線程檢出一個連接。如果你不希望出現這種情況,試試這個(改編自https://gist.github.com/limhoff-r7/71ee6b1568b604e131a8,這不僅是對Postgres的):

ActiveRecord::Base.establish_connection 

# Check if the spec passed to `ActiveRecord::Base.establish_connection` can connect to the database. 
# 
# @return [true] if an active connection can be made to the database using the current config. 
# @return [false] if an active connection cannot be made to the database. 
def connection_established? 
    begin 
    # use with_connection so the connection doesn't stay pinned to the thread. 
    ActiveRecord::Base.connection_pool.with_connection { 
     ActiveRecord::Base.connection.active? 
    } 
    rescue Exception 
    false 
    end 
end 
1

我同意@Luke英霍夫:這是手動的ActiveRecord的連接池簽出的連接,要手動返回到池中。 作爲一個說明,但是,我建議使用的連接即ActiveRecord的產生到塊

ActiveRecord::Base.connection_pool.with_connection { |con| con.active? } 

參照documentation of :with_connection