Using PostgreSQL with Python
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? These paid resources pick up where this lesson leaves off.
Project-based PostgreSQL video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked PostgreSQL books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.