To connect to a PostgreSQL database from a Python program, you need to import the psycopg2
module and create a new psycopg2.Connection
object. To create the connection object, you will need to provide the following information:
- The name of the host where the database server is running
- The port number where the database server is listening
- The user name and password to use for authentication
Here is an example of how to create a connection to a PostgreSQL database:
import psycopg2
# Replace "hostname", "port", "username", and "password" with the correct values
conn = psycopg2.connect(
host="hostname",
port=port,
user="username",
password="password"
)
Once you have created a
psycopg2.Connection
object, you can use it to create a new psycopg2.Cursor
object, which you can use to execute SQL queries and manage the database. Here is an example of how to create a cursor and execute a simple SQL query:import psycopg2
# Replace "hostname", "port", "username", and "password" with the correct values
conn = psycopg2.connect(
host="hostname",
port=port,
user="username",
password="password"
)
# Create a cursor
cur = conn.cursor()
# Execute a SQL query
cur.execute("SELECT * FROM my_table")
# Fetch the results of the query
results = cur.fetchall()
# Print the results
print(results)
Comments
Post a Comment