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

Foa*_*ebi 2 python multithreading psycopg2 python-multithreading

我在多线程 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)
Run Code Online (Sandbox Code Playgroud)

和:

Decoders(queue).start()
Decoders(queue).start()
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

数据库类:

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
Run Code Online (Sandbox Code Playgroud)

Mic*_*ard 6

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

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

  • @MichaelRobellard:OP 代码的结构方式,在任何插入可以运行之前,至少必须运行一个选择 * 必须*。无论哪个线程赢得比赛,都将在其中任何一个有机会插入任何内容之前进行选择。 (2认同)