gpt4 book ai didi

python - 如何在多线程Python程序中使用PostgreSQL

转载 作者:行者123 更新时间:2023-12-02 06:59:52 26 4
gpt4 key购买 nike

我正在多线程 python 程序中使用 psycopg2 (2.6) 连接到 PostgreSQL 数据库。

当程序中的队列大小增加时,选择查询会出现错误“没有可获取的结果”,但将记录插入数据库效果很好。

示例代码:

class Decoders(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue

def run(self):
self.decode()

def decode(self):
queue = self.queue
db = Database()
while queue.qsize() > 0:
# calling db methods, just an example
temp = queue.get()
db.select_records()
db.insert_record(temp)

和:

Decoders(queue).start()
Decoders(queue).start()

注意:我在多处理方面没有这个问题。

编辑:

当我只启动一个线程时,程序没有任何问题。

数据库类:

class Database:
db = object
cursor = object

def __init__(self):
self.db = connect(host=conf_hostname,
database=conf_dbname,
user=conf_dbuser,
password=conf_dbpass,
port=conf_dbport)
self.db.autocommit = True
self.cursor = self.db.cursor()

def select_records(self):
self.cursor.execute(simple select)
return self.cursor.fetchall()


def insert_record(self, temp):
# insert query

最佳答案

您是否为每个线程创建一个连接?如果您有多个线程,则需要每个线程都有一个连接(或一个在连接周围具有锁定机制的池),否则您将遇到各种奇怪的问题。

这就是为什么在多处理中不会出现问题,因为每个进程都会创建自己的连接。

关于python - 如何在多线程Python程序中使用PostgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32182405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com