import psycopg2
import time
import threading
def initiate():
conn = psycopg2.connect(host='localhost', user='postgres', password='password', port='5432', database='test')
conn.set_isolation_level(1)
conn.autocommit = False
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor3 = conn.cursor()
t1 = threading.Thread(target=test1, args=(cursor1, conn))
t2 = threading.Thread(target=test2, args=(cursor2, conn))
t3 = threading.Thread(target=test3, args=(cursor3, conn))
t1.start()
t2.start()
t3.start()
def test1(cursor, conn):
cursor.execute("INSERT INTO test_sch.tb_for_test1(col_for_t12, col_for_t13, col_for_t14) VALUES ('test_col1', 'test_col1', 1)")
time.sleep(10)
conn.commit()
cursor.close()
print("completed test1")
def test2(cursor, conn):
cursor.execute("INSERT INTO test_sch.tb_for_test1(col_for_t12, col_for_t13, col_for_t14) VALUES ('test_col2', 'test_col2', 2)")
time.sleep(5)
conn.commit()
cursor.close()
print("completed test2")
def test3(cursor, conn):
cursor.execute("INSERT INTO test_sch.tb_for_test1(col_for_t12, col_for_t13, col_for_t14) VALUES ('test_col3', 'test_col3', 3)")
time.sleep(15)
conn.commit()
cursor.close()
print("completed test3")
initiate()
在上面的代码中,我尝试使用运行三种不同方法的三个不同线程将三个记录插入数据库。方法test2完成后,它将提交所有三个记录,而不是等待方法test1和test3的事务。我可以理解,psycopg2事务是按连接而不是按游标进行的。那么关于如何将其移动到每个光标的任何建议?我的限制之一是不要打开太多连接