Welcome to this exciting tutorial on PostgreSQL with Python! In this lesson, we'll dive deep into using PostgreSQL, a powerful, open-source object-relational database management system, with Python. Let's get started!
PostgreSQL is a robust, advanced, and open-source relational database management system. It is popular for its robustness, scalability, and strong standards-compliance.
PostgreSQL is a great choice when working with Python because it offers:
Before we begin, you need to have PostgreSQL installed on your machine. Refer to our detailed guide on installing PostgreSQL.
First, let's connect to the PostgreSQL server and create a database.
import psycopg2
conn = psycopg2.connect(
dbname='postgres',
user='your_username',
password='your_password'
)
cursor = conn.cursor()
# Create a new database
cursor.execute('CREATE DATABASE my_database;')
# Connect to the newly created database
conn.close()
conn = psycopg2.connect(database='my_database')Next, we'll create a table to store our data.
# Create a table named 'users'
cursor.execute('''
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL
);
''')
conn.commit()š Note: We used the SERIAL type to automatically assign unique integer IDs to each row.
Now, let's insert some data into our 'users' table.
cursor.execute('INSERT INTO users (name, email) VALUES (%s, %s)', ('John Doe', 'john.doe@example.com'))
conn.commit()We can retrieve data from the 'users' table using a SQL query.
cursor.execute('SELECT * FROM users;')
results = cursor.fetchall()
for row in results:
print(row)Updating data is as simple as executing an SQL UPDATE query.
cursor.execute('UPDATE users SET email=%s WHERE id=%s', ('john.doe@newemail.com', 1))
conn.commit()To delete data, we use an SQL DELETE query.
cursor.execute('DELETE FROM users WHERE id=%s', (1,))
conn.commit()Which Python library do we use to interact with PostgreSQL?
Happy coding! š
Stay tuned for the advanced parts of this tutorial, where we'll explore more features of PostgreSQL and learn how to optimize your queries. š