Postgres (SQL) - Connect to Postgres database using Python
by
Jeremy Canfield |
Updated: November 25 2024
| Postgres (SQL) articles
The psycopg2 module can be used to connect to a Postgres database. pip install can be used to install the wheel and psycopg2-binary packages.
pip install wheel
pip install psycopg2-binary
And here is an example of how to connect to Postgres database. This is just a super simple example, with no error handling.
#!/usr/bin/python3
import psycopg2
db_name = "mydb"
db_host = "10.11.12.13"
db_user = "john.doe"
db_pass = "itsasecret"
db_port = "5432"
connection = psycopg2.connect(database=db_name,
host=db_host,
user=db_user,
password=db_pass,
port=db_port)
connection.close()
And here is an example that includes try / except / else / finally for error handling and timeout.
#!/usr/bin/python3
import psycopg2
import sys
db_name = "mydb"
db_host = "10.11.12.13"
db_user = "john.doe"
db_pass = "itsasecret"
db_port = "5432"
try:
connection = psycopg2.connect(database=db_name,
host=db_host,
user=db_user,
password=db_pass,
port=db_port,
timeout=3)
except Exception as exception:
print(f"got the following exception when attempting to connect to Postgres database {db_host}:{db_port}/{db_name} as {db_user}: {exception}")
sys.exit()
else:
print(f"Successfully connected to Postgres Database {db_host}:{db_port}/{db_name} as {db_user}")
try:
connection.close()
except Exception as exception:
print(f"got the following exception when attempting connection.close(): {exception}")
else:
print("Successfully disconnected from Postgres Database")
And here is an example of how to perform a fetchall query with no error handling.
#!/usr/bin/python3
import psycopg2
db_name = "mydb"
db_host = "10.11.12.13"
db_user = "john.doe"
db_pass = "itsasecret"
db_port = "5432"
connection = psycopg2.connect(database=db_name,
host=db_host,
user=db_user,
password=db_pass,
port=db_port)
cursor = connection.cursor()
cursor.execute("select * from mytable")
results = cursor.fetchall()
for row in results:
print(f"row 0 = {row[0]}")
print(f"row 1 = {row[1]}")
print(f"row 2 = {row[2]}")
cursor.close()
connection.close()
And here is an example of how to perform a fetchone query with no error handling.
#!/usr/bin/python3
import psycopg2
db_name = "mydb"
db_host = "10.11.12.13"
db_user = "john.doe"
db_pass = "itsasecret"
db_port = "5432"
connection = psycopg2.connect(database=db_name,
host=db_host,
user=db_user,
password=db_pass,
port=db_port)
cursor = connection.cursor()
cursor.execute("select * from mytable")
result = cursor.fetchone()
print(f"result = {result}")
print(f"result[0] = {result[0]}")
print(f"result[1] = {result[1]}")
cursor.close()
connection.close()
And here is an example of how to perform a statement with no error handling..
#!/usr/bin/python3
import psycopg2
from datetime import datetime
db_name = "mydb"
db_host = "10.11.12.13"
db_user = "john.doe"
db_pass = "itsasecret"
db_port = "5432"
connection = psycopg2.connect(database=db_name,
host=db_host,
user=db_user,
password=db_pass,
port=db_port)
cursor = connection.cursor()
statement = cursor.execute("update mytable set timestamp='{datetime.utcnow()}'")
connection.commit()
cursor.close()
connection.close()
And here is an example of how you can loop through the results.
#!/usr/bin/python3
import psycopg2
db_name = "mydb"
db_host = "10.11.12.13"
db_user = "john.doe"
db_pass = "itsasecret"
db_port = "5432"
connection = psycopg2.connect(database=db_name,
host=db_host,
user=db_user,
password=db_pass,
port=db_port)
cursor = connection.cursor()
cursor.execute("select * from mytable")
result = cursor.fetchone()
for row in result:
print(f"row[0] = {row[0]}")
print(f"row[1] = {row[1]}")
print(f"row[2] = {row[2]}")
cursor.close()
connection.close()
Did you find this article helpful?
If so, consider buying me a coffee over at