Using PostgreSQL with Python
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
Learn how to use PostgreSQL with Python to store and retrieve data.
Introduction to PostgreSQL
PostgreSQL is a powerful, open-source database system that allows you to store and manage large amounts of data. To get started with PostgreSQL, you'll need to install the psycopg2 package in Python. You can do this by running pip install psycopg2 in your terminal.
Connecting to PostgreSQL
To connect to a PostgreSQL database, you can use the following code:
import psycopg2
conn = psycopg2.connect(
host='localhost',
database='example',
user='username',
password='password'
)
cursor = conn.cursor()
This will connect to a PostgreSQL database on the local machine and create a cursor object.
Creating a Table
Once you have a database, you can create a table using the following code:
cursor.execute '''
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
)
'''```
This will create a new table called `users` with three columns: `id`, `name`, and `email`.
## Inserting Data
To insert data into the `users` table, you can use the following code:
```python
cursor.execute '''
INSERT INTO users (name, email)
VALUES ('John Doe', 'john@example.com')
'''```
This will insert a new row into the `users` table with the name `John Doe` and email `john@example.com`.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based PostgreSQL courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for PostgreSQL books — check the publication year so the examples match current versions.
Search Amazon →