Postgres (SQL) - fetchone query 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 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 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