批量从postgres数据库中获取数据(python) [英] Fetching data from postgres database in batch (python)

查看:84
本文介绍了批量从postgres数据库中获取数据(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Postgres 查询,其中我从 table1 中获取大约 2500 万行的数据,并希望将以下查询的输出写入多个文件.

I have the following Postgres query where I am fetching data from table1 with rows ~25 million and would like to write the output of the below query into multiple files.

query = """ WITH sequence AS (
                SELECT 
                        a,
                        b,
                        c
                FROM table1 )                    

select * from sequence;"""

下面是获取完整数据集的python脚本.如何修改脚本以将其提取到多个文件(例如,每个文件有 10000 行)

Below is the python script to fetch the complete dataset. How can I modify the script to fetch it to multiple files (eg. each file has 10000 rows)

#IMPORT LIBRARIES ########################
import psycopg2
from pandas import DataFrame

#CREATE DATABASE CONNECTION ########################
connect_str = "dbname='x' user='x' host='x' " "password='x' port = x"
conn = psycopg2.connect(connect_str)
cur = conn.cursor()
conn.autocommit = True

cur.execute(query)
df = DataFrame(cur.fetchall())

谢谢

推荐答案

这里有 3 个可能有用的方法

Here are 3 methods that may help

  1. 使用 psycopg2 命名游标 cursor.itersize = 2000

片段

 with conn.cursor(name='fetch_large_result') as cursor:

    cursor.itersize = 20000

    query = "SELECT * FROM ..."
    cursor.execute(query)

    for row in cursor:
....

  1. 使用 psycopg2 命名游标 fetchmany(size=2000)

片段

conn = psycopg2.connect(conn_url)
cursor = conn.cursor(name='fetch_large_result')
cursor.execute('SELECT * FROM <large_table>')

while True:
    # consume result over a series of iterations
    # with each iteration fetching 2000 records
    records = cursor.fetchmany(size=2000)

    if not records:
        break

    for r in records:
        ....

cursor.close() #  cleanup
conn.close()

最后你可以定义一个 SCROLL CURSOR

Finally you could define the a SCROLL CURSOR

  1. 定义滚动光标

片段

BEGIN MY_WORK;
-- Set up a cursor:
DECLARE scroll_cursor_bd SCROLL CURSOR FOR SELECT * FROM My_Table;

-- Fetch the first 5 rows in the cursor scroll_cursor_bd:

FETCH FORWARD 5 FROM scroll_cursor_bd;
CLOSE scroll_cursor_bd;
COMMIT MY_WORK;

请注意未在 psycopg2 中命名游标将导致游标在客户端而不是服务器端.

Please note Not naming the cursor in psycopg2 will cause the cursor to be client side as opposed to server side.

这篇关于批量从postgres数据库中获取数据(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆