puk*_*puk 5 postgresql psycopg2 python-3.x psql
我觉得我的问题的答案就在这两个问题中,但我发现答案的措辞非常糟糕(或高于我的薪资等级)
问题:使用 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()
Run Code Online (Sandbox Code Playgroud)
选项 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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3330 次 |
| 最近记录: |