【问题标题】:Is it possible to close/reopen connection using pd.read_sql and chunking?是否可以使用 pd.read_sql 和分块来关闭/重新打开连接?
【发布时间】:2021-03-18 04:27:08
【问题描述】:

假设我有一个非常大的表,我想使用 pd.read_sql 和 chunksize = 10000。

我现在的处理方式是:

from sqlalchemy import create_engine
import pandas as pd

engine = create_engine('dialect://user:pass@host:port/schema')
with engine.connect() as conn:
  for df in pd.read_sql('SELECT * FROM VERY_LARGE_TABLE', con=conn, chunksize=10000):
    do stuff

我的问题(使用雪花作为数据源)是连接将在“做事”中途过期。

是否可以这样做:

engine = create_engine('dialect://user:pass@host:port/schema', echo=False)
# chunk 1
with engine.connect() as conn:
  df = pd.read_sql('SELECT * FROM VERY_LARGE_TABLE', con=conn)
do stuff

# chunk 2
with engine.connect() as conn:
  df = pd.read_sql('SELECT * FROM VERY_LARGE_TABLE', con=conn)
do stuff

我现在正在探索的替代方法是在引擎中设置connect_args={"client_session_keep_alive": True}

【问题讨论】:

    标签: pandas sqlalchemy snowflake-cloud-data-platform


    【解决方案1】:

    你能做这样的事情吗:

    start = 0
    chunk = 5000
    
    while True:
    
        with engine.connect() as conn:
            query = f'SELECT * FROM VERY_LARGE_TABLE LIMIT {start}, {chunk}'
            df = pd.read_sql(query, con=conn)
        
            # if df is empty stop querying
            if df.empty: 
                break
            else:         # increase start for next iteration
                start += chunk
            
        do stuff
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多