Installing psycopg2 on Mac M1
psycopg2 is a PostgreSQL database adapter for Python. To install psycopg2 on an M1 Mac, you need to follow these steps:
- Install Homebrew:
- Install PostgreSQL:
- Install dependencies:
- Install psycopg2:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew install postgresql
brew install openssl readline
pip install psycopg2-binary
After following these steps, psycopg2 should be successfully installed on your Mac M1.
Example Usage
Here’s a simple example of using psycopg2 to connect to a PostgreSQL database in Python:
import psycopg2
# Connect to the PostgreSQL database
conn = psycopg2.connect(
host="localhost",
port="5432",
database="mydatabase",
user="myuser",
password="mypassword"
)
# Create a cursor
cursor = conn.cursor()
# Execute a query
cursor.execute("SELECT * FROM mytable")
# Fetch all rows
rows = cursor.fetchall()
# Print the rows
for row in rows:
print(row)
# Close the cursor and connection
cursor.close()
conn.close()