[Python] Return Pandas dataframe from PostgreSQL query with sqlalchemy

Discussão em 'Python' iniciado por Stack, Fevereiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I want to query a PostgreSQL database and return the output as a Pandas dataframe.

    I created a connection to the database with 'SqlAlchemy':

    from sqlalchemy import create_engine
    engine = create_engine('postgresql://user@localhost:5432/mydb')


    I write a Pandas dataframe to a database table:

    i=pd.read_csv(path)
    i.to_sql('Stat_Table',engine,if_exists='replace')


    Based on the docs, looks like pd.read_sql_query() should accept a SQLAlchemy engine:

    a=pd.read_sql_query('select * from Stat_Table',con=engine)


    But it throws an error:

    ProgrammingError: (ProgrammingError) relation "stat_table" does not exist


    I'm using Pandas version 0.14.1.

    What's the right way to do this?

    Continue reading...

Compartilhe esta Página