Junior — Middle
How is the connection to a PostgreSQL database established?
sobes.tech AI
Answer from AI
Connecting to a PostgreSQL database in Python is usually done using the psycopg2 or asyncpg library for asynchronous access.
Example of connection using psycopg2:
import psycopg2
try:
connection = psycopg2.connect(
dbname="your_db_name",
user="your_username",
password="your_password",
host="localhost",
port="5432"
)
cursor = connection.cursor()
cursor.execute('SELECT version();')
db_version = cursor.fetchone()
print(f"Connected to - {db_version}")
except Exception as error:
print(f"Error connecting to PostgreSQL: {error}")
finally:
if connection:
cursor.close()
connection.close()
This example creates a connection to the database, executes a simple query, and closes the connection.