首页 > 解决方案 > 使用python从PostgreSql中选择大量行非常慢

问题描述

我正在尝试使用 python 执行选择查询,它有超过 200,000 个结果/行。在 DB_EN​​GINE(Dbeaver) 上输出 200,000 行的相同查询大约需要 10-15 秒,但在尝试使用 python 执行它时,大约需要 6 分钟。我正在使用 psycopg2,SQLALCHEMY 引擎。

engine = create_engine(SQLALCHEMY_DATABASE_URI, poolclass=NullPool)
conn = engine.raw_connection()
cursor = conn.cursor()
cursor.execute(query)

任何人都可以建议将其优化到 Dbeaver 输出时间水平的方法。

尝试的其他方法:

第2部分:

    with tempfile.TemporaryFile() as tmpfile:
        copy_sql = "COPY ({query}) TO STDOUT WITH CSV {head}".format(
            query=query, head="HEADER"
        )
        conn = engine.raw_connection()
        cur = conn.cursor()
        cur.copy_expert(copy_sql, tmpfile)
        tmpfile.seek(0)
        df = pd.read_csv(tmpfile)
        tmpfile.close()

标签: pythonsqlpostgresql

解决方案


推荐阅读