如何在Python/psycopg2中同时执行多个独立语句?

2024-04-29 03:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在PostgreSQL中有三个具体化视图,它们需要很长时间刷新(每个视图超过几个小时),我需要每天刷新它们。在

我目前正在使用一个Python脚本来逐个刷新视图,但是与在pgAdmin中手动刷新视图相比,所需的时间是手动刷新时间的三倍(在pgAdmin中,我可以在不同的选项卡中同时运行三次刷新)。在

我的代码现在是这样的:

import psycopg2
config = {'connection details'}
conn = psycopg2.connect(**config)
cur = conn.cursor()

# This is the part that I want to run simultaneously
cur.execute('REFRESH MATERIALIZED VIEW gsam.mv_hist_wip_data')
cur.execute('REFRESH MATERIALIZED VIEW gsam.mv_hist_ver_data')
cur.execute('REFRESH MATERIALIZED VIEW gsam.mv_hist_verda_data')

conn.close()

如何使用Python和psycopg2同时执行三个REFRESH MATERIALIZED VIEW语句?在


Tags: view视图executedata时间手动connrefresh
1条回答
网友
1楼 · 发布于 2024-04-29 03:27:39

您可以使用多处理池请检查文档here。并检查下面的例子

import psycopg2
from multiprocessing import Pool

def main():
    p = Pool(processes=3)
    view_names = ['mv_hist_wip_data','mv_hist_ver_data', 'mv_hist_verda_data']
    result = p.map(refresh_view, view_names)

def  refresh_view(view_name):

    config = {'connection details'}
    conn = psycopg2.connect(**config)
    cur = conn.cursor()
    # This is the part that I want to run simultaneously
    cur.execute('REFRESH MATERIALIZED VIEW gsam.%s', (view_name,))
    conn.close()

相关问题 更多 >