[Python] Update created engine in sqlacemy

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I've created database using the following code:

    from sqlalchemy import create_engine, text

    db_user = 'postgres'
    db_password = 'chnageme'
    db_host = '12.123.123.123'
    db_port = '5432'
    db_name = 'new_db'
    # Create a connection string to connect to the PostgreSQL server
    connection_string = f'postgresql://{db_user}:{db_password}@{db_host}:{db_port}/'

    # Create an SQLAlchemy engine
    engine = create_engine(connection_string)

    # Check if the database exists and create it if it doesn't
    with engine.connect() as connection:
    result = connection.execute(text("SELECT 1 FROM pg_database WHERE datname = :db_name"), {"db_name": db_name})
    if not result.fetchone():
    connection.execute(f"CREATE DATABASE \"{db_name}\";")
    print(f"Database '{db_name}' created successfully.")
    else:
    print(f"Database '{db_name}' already exists.")

    engine = create_engine(f'{connection_string}{db_name}')


    Now I'm wondering if there is an option\function to update original engine :

    engine = create_engine(connection_string)


    Instead of creating new one later on?

    engine = create_engine(rf'{connection_string}{db_name}')

    Continue reading...

Compartilhe esta Página