2012-02-15 61 views
4

我已經開始使用mysql2 gem。我試圖找出一些基本的東西 - 其中之一是如何顯式執行事務(對於批處理操作,如多個INSERT/UPDATE查詢)。如何使用ruby mysql2執行交易

在舊ruby-mysql,這是我的方法:

client = Mysql.real_connect(...) 
inserts = [ 
    "INSERT INTO ...", 
    "UPDATE .. WHERE id=..", 
    # etc 
] 

client.autocommit(false) 
inserts.each do |ins| 
    begin 
    client.query(ins) 
    rescue 
    # handle errors or abort entirely 
    end 
end 
client.commit 

我無法找到的文檔太多 - 如何同與mysql2做了什麼?

回答

2

這個問題讓我很好奇,所以我找到了Ruby on Rails的如何處理事務,我發現this code

def begin_db_transaction 
    execute "BEGIN" 
rescue Exception 
    # Transactions aren't supported 
end 

def commit_db_transaction #:nodoc: 
    execute "COMMIT" 
rescue Exception 
    # Transactions aren't supported 
end 

def rollback_db_transaction #:nodoc: 
    execute "ROLLBACK" 
rescue Exception 
    # Transactions aren't supported 
end 

您是否嘗試過執行在你的其他語句begincommit聲明?

client.query('begin') 

inserts.each do |ins| 
    begin 
    client.query(ins) 
    rescue 
    client.query('rollback') 
    return 
    end 
end 

client.query('commit') 
7

我只是做了實現:

class DBConnector 
    def transaction(&block) 
    raise ArgumentError, "No block was given" unless block_given? 
    begin 
     client.query("BEGIN") 
     yield 
     client.query("COMMIT") 
    rescue 
     client.query("ROLLBACK") 
    end 
    end 
end 

所以,你可以使用這樣的:

DBConnector.transaction do 
    # your db queries here 
end 
0

使用布魯諾的模板,然後將交易狀態指示燈:

def transaction(&block) 
    raise ArgumentError, "No block was given" unless block_given? 
    begin 
     raw_query("BEGIN") 
     yield 
     raw_query("COMMIT") 
     return true # Successful Transaction 
    rescue 
     raw_query("ROLLBACK") 
     return false # Failed Transaction 
    end 
end 

互動與#交易:

def run_queries(queries) 
    raise ArgumentError, "Invalid Queries Argument: #{queries}" unless queries.respond_to?(:each) 
    success = transaction do 
     queries.each do |q| 
      raw_query(q) 
     end 
    end 
    raise RuntimeError, "Transaction Failed for Queries: #{queries}" unless success 
end