Postgres (SQL) - Update statement 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 in Python. 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 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()
Did you find this article helpful?
If so, consider buying me a coffee over at