多线程的psycopg2和Python没有返回结果

4 投票
1 回答
1126 浏览
提问于 2025-04-17 14:55

我有一个程序,父进程连接了数据库,而每个子进程都有自己的数据库连接(在构造函数中创建),使用的是Python 2.6和psycopg2库。

每5秒,父进程会查询数据库,以获取子进程的进度报告。每个子进程都在做一些事情,并把它们当前的步骤存储在数据库中。

下面是我简化后的代码示例:

def getStatus( conn ):
    query = "select job_name, status from job_status_table"
    cursor = conn.getCursor()
    cursor.execute( query )
    return cursor.fetchAll()


def simpleStatus():
    conn = DBInit()
    # output is correct here
    print getStatus( conn )
    queue = getJobList( conn )
    for q in queue:
        p = multiprocessing.Process( target=run, args=q )
        p.start()
    while: # condition that does terminate, not germane
        time.sleep( 5 )
        # output is incorrect here
        print getStatus( conn )
    ...

在子进程内部,它调用了以下内容:

def updateStatus( self, status_i ):
    update = "update job_status_table set status='%s' where job_name='%s'"%( status_i, self.name )
    cursor = self.conn.getCursor()
    cursor.execute( update )
    self.conn.commit()

通过外部查询数据库(psql),可以看到在程序运行时,查询返回的结果是正确的。然而,在程序内部却不是这样。如果我在time.sleep调用后重新初始化数据库,输出就会正确。为什么会这样呢?

1 个回答

3

父进程在自己的事务中,直到它结束这个事务(通过commit()或rollback()),它才会看到任何变化。你有两个选择:

  1. 把父进程的连接设置为自动提交模式(conn.autocommit = True);或者
  2. 在执行你的查询之前,先在连接上执行commit()或rollback(),这样可以确保在一个新的、最新的事务中执行查询。

撰写回答