2014-09-23 41 views
0

這裏是我的方法是不是好,不要關閉分貝sqlite3的

def convertElsToMass(symbol) 
    begin 
     db = SQLite3::Database.open("test.db") 

     rs = db.prepare("SELECT * FROM Elements WHERE symbol = '#{symbol} '") 
     temp = rs.execute 
     mass = temp.first 

     rescue SQLite3::Exeption => e 
      puts e 

     ensure 
      db.close if db 
    end  
    return mass[3] 
end 

當我測試這個方法使用RSpec的我收到此錯誤信息:

1) PeriodicTable should change Elements to mass of Elements 
Failure/Error: expect(table.convertElsToMass("Na")).to eq(22.9898) 
SQLite3::BusyException: 
    unable to close due to unfinalized statements or unfinished backups 
# ./lib/formatel.rb:42:in `close' 
# ./lib/formatel.rb:42:in `convertElsToMass' 
# ./spec/lib/pt_spec.rb:13:in `block (2 levels) in <top (required)>' 

我注意到我,如果我不」 t放行db.close if db這個方法的確如我所料。然而,我擔心如果我在執行查詢後不關閉數據庫會導致什麼後果。我該如何解決這個問題,以便在執行查詢後關閉數據庫?

回答

1

您不必擔心關閉數據庫。當您撥打prepareexecute時,這些呼叫在完成時自動關閉。有一個內部的rescue/ensure塊可以確保即使發生錯誤,db也會關閉。你可以在SQLite3::Database的源代碼中看到這個。

+0

關閉語句,而不是數據庫。 – 2017-09-01 03:05:32