Created
August 11, 2020 18:37
-
-
Save akarsh1995/96d9f3aa8095fccb7e5ca867c122ab0d to your computer and use it in GitHub Desktop.
For aspiring database administrators. Create database connection using python's SQLAlchemy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| SQLAlchemy | |
| psycopg2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment