[Python] postgresql how to change column in python

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I accidentally wrote a bunch of tables with abbreviated column names and want to edit them.

    obviously

    ALTER TABLE [$table_name]
    RENAME COLUMN "h" TO "high";

    ALTER TABLE [$table_name]
    RENAME COLUMN "v" TO "volume";

    ALTER TABLE [$table_name]
    RENAME COLUMN "o" TO "open";


    etc, works in Navicat but I'd have to search separately and type in each table name one by one plus if one of the columns is not found for any reason, it just stops the rest of the query. Anyway, I tried

    with engine.connect() as conn:
    inspector = inspect(engine)
    for table_name in inspector.get_table_names():
    columns = [col["name"] for col in inspector.get_columns(table_name)]
    if x in columns:
    # Generate and execute the ALTER TABLE command
    query = text(f'ALTER TABLE "{table_name}" RENAME COLUMN "{x}" TO "{y}";')
    conn.execute(query)
    columns = [col["name"] for col in inspector.get_columns(f"{table_name}")]
    print("Updated columns:", columns)
    print(f'Renamed column "{x}" to "{y}" in table "{table_name}".')


    in python and while the print statements will tell me everything changed fine, the actual columns will remain unchanged.

    ps - and if anyone knows how I would be able to automate this in navicat? Automate seems to just run a query multiple times without my being able to change the parameters, how can I loop through, get a list, and change the tables listed?

    Continue reading...

Compartilhe esta Página