Created
October 2, 2022 16:29
-
-
Save iKunalChhabra/2a4658dbc9ae66c8743f63fb3b329503 to your computer and use it in GitHub Desktop.
Connect to postgreSQL in Python
This file contains 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
import psycopg2 | |
import logging | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.INFO) | |
logging.basicConfig( | |
format='%(asctime)s %(levelname)-8s %(message)s', | |
level=logging.INFO, | |
datefmt='%Y-%m-%d %H:%M:%S') | |
def execute_query(query): | |
conn = psycopg2.connect(dbname='myapp', # todo : use config | |
user='myapp', | |
password='password', | |
host='localhost') | |
logger.info('Connected to database') | |
cur = conn.cursor() | |
logger.info('Cursor created') | |
logger.info(query) | |
cur.execute(query) | |
column_names = [desc[0] for desc in cur.description] | |
try: | |
for row in cur: | |
yield dict(zip(column_names, row)) | |
except Exception as e: | |
logger.error(e) | |
finally: | |
cur.close() | |
logger.info('Closed cursor') | |
conn.close() | |
logger.info('Disconnected from database') | |
if __name__ == '__main__': | |
query = "SELECT username, email_id FROM instagram.users where username ilike '%Kunal%'" | |
for record in execute_query(query): | |
print(record['username']) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment