首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多线程python psycopg2

多线程python psycopg2
EN

Stack Overflow用户
提问于 2018-02-05 19:55:59
回答 1查看 6.2K关注 0票数 2

我在python的程序中使用多线程。我排了三个队。在其中一个中,我将数据插入postgres数据库。但在此之前,我需要检查数据库中是否已经存在带有特定域名的行。所以我有:

代码语言:javascript
复制
class AnotherThread(threading.Thread):
    def __init__(self, another_queue):
        threading.Thread.__init__(self)
        self.another_queue = another_queue


    def run(self):
        while True:
            chunk = self.another_queue.get()
            if chunk is not '':
                dane = chunk[0].split(',',2)

                cur.execute("SELECT exists(SELECT 1 FROM global where domain = %s ) ", (domena,))
                jest = cur.fetchone()
                print(jest)

这是我第三个队列代码的一部分。我在这里连接到数据库(在main()函数中):

代码语言:javascript
复制
queue = Queue.Queue()
out_queue = Queue.Queue()
another_queue = Queue.Queue()

for i in range(50):
    t = ThreadUrl(queue, out_queue)
    t.setDaemon(True)
    t.start()

for host in hosts:
    queue.put(host)

for i in range(50):
    dt = DatamineThread(out_queue,another_queue)
    dt.setDaemon(True)
    dt.start()

conn_str = "dbname='{db}' user='user' host='localhost' password='pass'"
conn = psycopg2.connect(conn_str.format(db='test'))
conn.autocommit = True
cur = conn.cursor()

for i in range(50):
    dt = AnotherThread(another_queue)
    dt.setDaemon(True)
    dt.start()



queue.join()
out_queue.join()
another_queue.join()

cur.close()
conn.close()

当我运行我的脚本时,我得到了:

代码语言:javascript
复制
(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
(False,)
Exception in thread Thread-128:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "domains.py", line 242, in run
    jest = cur.fetchone()
ProgrammingError: no results to fetch

Exception in thread Thread-127:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "domains.py", line 242, in run
    jest = cur.fetchone()
ProgrammingError: no results to fetch

(False,)
(False,)
(False,)

为什么他们中的一些人会犯错误?

EN

回答 1

Stack Overflow用户

发布于 2018-02-05 20:20:24

这可能与所有线程共享相同的连接和游标有关。我可以想象,在这样的情况下,cur.execute()被运行,然后cur.fetchone()由另一个线程运行,然后cur.fetchone()再次被线程运行(又是另一个线程,还是同一个线程或前一个线程),其间没有cur.execute。Python将在每一行线程之间切换(语句)。因此,第二次运行fetchone()时,就没有结果了:最初只有一行要获取,现在已经耗尽了。

您可能希望隔离每个游标,或者以某种方式使cur.execute(...); cur.fetchone()命令具有原子性。

are transactions in postgresql via psycopg2 per cursor or per connection (DBA StackExchange链接)问题的答案是每个连接都有事务,所以隔离游标可能对您没有帮助。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48630476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档