Created
September 8, 2021 23:59
-
-
Save zobayer1/8f74abdf19d4dc3c1d5a56dd582650cf to your computer and use it in GitHub Desktop.
A simple python snippet for connecting to PostgreSQL database using psycopg2 library.
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
"""PostgreSQL Connect | |
A simple python snippet for connecting to PostgreSQL database using psycopg2 library. | |
Installl psycopg2: | |
sudo dnf install python3-devel postgresql-devel | |
pip install psycopg2 | |
""" | |
import psycopg2 | |
"""DB URI: PostgreSQL connection URI | |
Replace the curly braced variables with real values. If your password contains special characters, | |
you have to pass it as a query parameters. | |
""" | |
uri = "postgresql://{username}:{password}@{host}:{port}/{db}?options=-csearch_path%3D{schema},public" | |
pg_connection = psycopg2.connect(uri) | |
query = """ | |
SELECT user_id FROM user_table WHERE status = %(status)s | |
""" | |
with pg_connection.cursor() as cursor: | |
cursor.execute( | |
query, | |
{ | |
"status": "active", | |
}, | |
) | |
rows = cursor.fetchall() | |
for row in rows: | |
print(row) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment