python - 使用python从PostgreSql中选择大量行非常慢
问题描述
我正在尝试使用 python 执行选择查询,它有超过 200,000 个结果/行。在 DB_ENGINE(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 输出时间水平的方法。
尝试的其他方法:
第1部分:
df = pd.DataFrame() dfl = [] for chunk in pd.read_sql_query( query, con=engine ,chunksize=5000): print('chunk from PSQL', chunk) # Start Appending Data Chunks from PSQL Result set into List dfl.append(chunk) # Start appending data from list to dataframe df = pd.concat(dfl, ignore_index=True)
第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()
解决方案
推荐阅读
- html - 为什么这个 html 表格会在桌面上响应,而不是在移动设备上?
- docker - 在 dockerfile 中运行 bash 文件
- angular - CI 'ng build' 找不到打字稿文件,而本地构建可以
- reactjs - 如何将数组从 React 应用程序发送到 Flask 应用程序
- python - seaborn中带有子图的散点图
- bash - 存储别名的更好方法?
- ruby-on-rails - 获取并汇总所有关联的数据
- python - VBA 可以在我不指定路径的情况下识别 Python 位置吗?
- r - 使用 data.table 在多次熔化期间命名变量
- git - 为什么 git commit --author "name" 仍然无法提交错误 "empty ident name"