Skip to content

Instantly share code, notes, and snippets.

@akarsh1995
Created August 11, 2020 18:37
Show Gist options
  • Select an option

  • Save akarsh1995/96d9f3aa8095fccb7e5ca867c122ab0d to your computer and use it in GitHub Desktop.

Select an option

Save akarsh1995/96d9f3aa8095fccb7e5ca867c122ab0d to your computer and use it in GitHub Desktop.
For aspiring database administrators. Create database connection using python's SQLAlchemy.
from sqlalchemy import create_engine
default_query = ("select * from pg_catalog.pg_tables where schemaname !="
"'information_schema' and schemaname != 'pg_catalog'")
def create_engine_custom(username, password=None, host='localhost', db=None):
password = ':' + password if password else ''
db = db if db else ''
engine = create_engine(f'postgresql+psycopg2://{username}{password}@{host}/{db}')
return engine
def execute_query_return_rows(query, engine):
engine.connect()
result = engine.execute(query)
return result.fetchall()
if __name__ == '__main__':
query = default_query
print('Use file to change the host.')
engine = create_engine_custom(username=input("db_username > "),
password=input("password > "))
engine.connect()
rows = execute_query_return_rows(query, engine)
tables_name = [row[1] for row in rows]
print(tables_name)
SQLAlchemy
psycopg2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment