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

标签 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)

和:

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/

相关文章:

postgresql - 如何使用 pandas sqlalchemy 和 psycopg2 处理 NaT

java - 为什么要在 invokeAll 方法之后调用 join 呢?

java - 在java中的多线程之间维护相同的同步数组列表

python - 在 python psycopg2 中通过列名检索值

从 JSON 模式生成 Python JSON 虚拟数据

java - ThreadLocal 与新局部变量相比的真正优势

python - 如何从 [PostgreSQL] 数据库以 [HTML] 形式显示我的 [Django] 模型的结果?

python - 在扭曲中使用线程

python - 无法使用 tf.reduce_sum() 优化,但使用 tf.reduce_mean() 成功

python - 将自身数据传递给递归函数