【发布时间】:2021-02-12 13:12:21
【问题描述】:
我觉得我的问题的答案在这两个 SO 问题中,但我发现答案的措辞非常糟糕(或高于我的工资等级)
- multi thread python psycopg2
- Are transactions in PostgreSQL via
psycopg2per-cursor or per-connection?
问题:使用 psycopg2 确保线程安全的正确方法是什么
选项 1:每个线程都有自己的光标
import threading
import psycopg2
conn = psycopg2.connect (
host=127.0.0.1,
user='john',
password='1234',
dbname='foo',
port=1234)
class Foo (threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
def run (self):
global conn
cur = conn.cursor()
sql_query="SELECT * from foo;"
print(cur.execute (sql_query))
conn.commit()
num_threads = 100
threads = []
for i in seq (num_threads):
threads.append (Foo())
for i in seq (num_threads):
threads[i].start()
for i in seq (num_threads):
threads[i].join()
选项 2:每个线程都有自己的连接
import threading
import psycopg2
db_conn = psycopg2.connect (
host=127.0.0.1,
user='john',
password='1234',
dbname='foo',
port=1234)
class Foo (threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.conn = psycopg2.connect (
host=127.0.0.1,
user='john',
password='1234',
dbname='foo',
port=1234)
def run (self):
cur = self.conn.cursor()
sql_query="SELECT * from foo;"
print(cur.execute (sql_query))
conn.commit()
num_threads = 100
threads = []
for i in seq (num_threads):
threads.append (Foo())
for i in seq (num_threads):
threads[i].start()
for i in seq (num_threads):
threads[i].join()
【问题讨论】:
标签: python-3.x postgresql psycopg2 psql