2016-06-22 8 views
2

データベース照会には2つの機能があります。別の2つのクエリを仮定して、これらを並列に実行して同じデータベースをクエリする方法と、残りのコードの実行を続ける前に両方の結果が返るのを待つ方法はありますか?ここでpythonを使用してデータベースを並列に照会する方法

def query1(param1, param2): 
    result = None 
    logging.info("Connecting to database...") 
    try: 
     conn = connect(host=host, port=port, database=db) 
     curs = conn.cursor() 
     curs.execute(query) 
     result = curs 
     curs.close() 
     conn.close() 
    except Exception as e: 
     logging.error("Unable to access database %s" % str(e)) 
    return result 


def query2(param1, param2): 
    result = None 
    logging.info("Connecting to database...") 
    try: 
     conn = connect(host=host, port=port, database=db) 
     curs = conn.cursor() 
     curs.execute(query) 
     result = curs 
     curs.close() 
     conn.close() 
    except Exception as e: 
     logging.error("Unable to access database %s" % str(e))  
    return result 
+0

私はあなたが[ 'threading'](httpsに見てみることができますね://ドキュメント.python.org/3/library/threading.html)ライブラリを標準コレクションから削除します。ここでは、pythonスレッドを使用する方法(および戻り値を収集する方法)について説明しています。http://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread- in-python(これは実際にはPython側での並列処理ではありませんが、両方の要求はほぼ同時に行われます)。 – mgc

答えて

3

はあなたが達成しようとしている何をマルチスレッドコードです:

from threading import Thread, Lock 

class DatabaseWorker(Thread): 
    __lock = Lock() 

    def __init__(self, db, query, result_queue): 
     Thread.__init__(self) 
     self.db = db 
     self.query = query 
     self.result_queue = result_queue 

    def run(self): 
     result = None 
     logging.info("Connecting to database...") 
     try: 
      conn = connect(host=host, port=port, database=self.db) 
      curs = conn.cursor() 
      curs.execute(self.query) 
      result = curs 
      curs.close() 
      conn.close() 
     except Exception as e: 
      logging.error("Unable to access database %s" % str(e)) 
     self.result_queue.append(result) 

delay = 1 
result_queue = [] 
worker1 = DatabaseWorker("db1", "select something from sometable", 
     result_queue) 
worker2 = DatabaseWorker("db1", "select something from othertable", 
     result_queue) 
worker1.start() 
worker2.start() 

# Wait for the job to be done 
while len(result_queue) < 2: 
    sleep(delay) 
job_done = True 
worker1.join() 
worker2.join() 
+0

@ th3an0malyに感謝しますが、q1とq2は何ですか? – ArchieTiger

+0

おっと、申し訳ありません。それらを 'worker1'と' worker2'に編集しました。これらの変数名を使ってテストを書いた後、コードに合わせて変更しました:) – th3an0maly

+0

ありがとう!ところで、私は 'result_queue.size <2'にエラーがあります。そのリストには属性サイズがありません。したがって、 'result_queue.size <2'を' len(result_queue)<2'に変更しました。そして、どのように私は両方の労働者から個々の結果にアクセスできますか? – ArchieTiger

関連する問題