Bootstrap FreeKB - Postgres (SQL) - Update statement using Python
Postgres (SQL) - Update statement using Python

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter c53d0c in the box below so that we can be sure you are a human.