[Python] sqlalchemy insert PRAGMA statement while dealing with postgresql database

Discussão em 'Python' iniciado por Stack, Junho 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to migrate a small table on local SQLite database to a remote postgresql server, but I'm getting error message "(psycopg2.errors.SyntaxError) syntax error at or near "PRAGMA" LINE 1: PRAGMA foreign_keys=ON". This is my code:

    from sqlalchemy import create_engine, select, insert
    import sqlalchemy.orm as so
    import psycopg2
    import pandas as pd
    from config import Config
    import os
    from dotenv import load_dotenv
    from app.models import Grupo

    # Creating engines
    load_dotenv()
    sqlite_engine = create_engine(Config.SQLALCHEMY_DATABASE_URI)
    postgres_url = f"postgresql+psycopg2://{os.getenv('PGUSER')}:{os.getenv('PGPASSWORD')}@{os.getenv('PGHOST')}:{os.getenv('PGPORT')}/{os.getenv('PGDATABASE')}"
    postgres_engine = create_engine(postgres_url)

    # Reading table from SQLite
    stmt = select(Grupo)
    df_Grupo = pd.read_sql(sql=stmt, con=sqlite_engine)
    # a small, non important change
    df_Grupo['DT_COMPETENCIA'] = df_Grupo['DT_COMPETENCIA'].str[:4] + '-' + df_Grupo['DT_COMPETENCIA'].str[4:]

    # Writing table on postgresql
    with so.Session(postgres_engine) as pg_session:
    try:
    pg_session.execute(insert(Grupo), df_Grupo.to_dict(orient='records'))
    pg_session.commit()
    except Exception as e:
    print(f"Erro na migração da tabela Grupo: \n{e}")


    This is the output:

    Erro na migração da tabela Grupo:
    (psycopg2.errors.SyntaxError) syntax error at or near "PRAGMA"
    LINE 1: PRAGMA foreign_keys=ON
    ^

    (Background on this error at: https://sqlalche.me/e/20/f405)


    An this is the complete table:


    CO_GRUPO NO_GRUPO DT_COMPETENCIA
    0 01 Ações de promoção e prevenção em saúde 2024-06
    1 02 Procedimentos com finalidade diagnóstica 2024-06
    2 03 Procedimentos clínicos 2024-06
    3 04 Procedimentos cirúrgicos 2024-06
    4 05 Transplantes de orgãos, tecidos e células 2024-06
    5 06 Medicamentos 2024-06
    6 07 Órteses, próteses e materiais especiais 2024-06
    7 08 Ações complementares da atenção à saúde 2024-06
    8 09 Procedimentos para Ofertas de Cuidados Integrados 2024-06

    Continue reading...

Compartilhe esta Página