Pandas writing dataframe to other postgresql schema

后端 未结 2 775
南方客
南方客 2020-12-15 07:35

I am trying to write a pandas DataFrame to a PostgreSQL database, using a schema-qualified table.

I use the following code:

import pandas.io.sql as p         


        
2条回答
  •  借酒劲吻你
    2020-12-15 08:07

    Solved, thanks to joris answer. Code was also improved thanks to joris comment, by passing around sqlalchemy engine instead of connection objects.

    import pandas as pd
    from sqlalchemy import create_engine, MetaData
    
    engine = create_engine(r'postgresql://some:user@host/db')
    meta = sqlalchemy.MetaData(engine, schema='a_schema')
    meta.reflect(engine, schema='a_schema')
    pdsql = pd.io.sql.PandasSQLAlchemy(engine, meta=meta)
    
    df = pd.read_sql("SELECT * FROM xxx", con=engine)    
    pdsql.to_sql(df, 'test')
    

提交回复
热议问题