Peewee is a lightweight object-relational mapping (ORM) library for Python that provides a simple and intuitive way to interact with databases. In this blog post, we will explore how to use Peewee with SQLite, one of the most popular relational database management systems (RDBMS).
Prerequisites
Before we start, make sure you have the following installed:
- Python 3.x
- SQLite
Installation
To install Peewee, open your command prompt and run the following command:
pip install peewee
Setting up a SQLite database
First, create a new Python file and import the necessary modules:
from peewee import *
Next, let’s define our database and create a connection to our SQLite file-based database:
database = SqliteDatabase('mydatabase.db')
Defining a model
Now, let’s define a model for our database. A model represents a table in the database and the fields/columns it contains. To define a model, create a new class that inherits from peewee.Model
:
class User(Model):
name = CharField()
age = IntegerField()
email = CharField(unique=True)
class Meta:
database = database
In the example above, we’ve defined a User
model with three fields: name
, age
, and email
. We’ve also specified that the email
field should be unique.
Creating tables
Before we can start using our database, we need to create the necessary tables. To create the tables, we can use the create_tables
method provided by Peewee:
database.create_tables([User])
This will create the User
table in our SQLite database.
Inserting data
Now, let’s insert some data into our User
table:
user = User(name='John Doe', age=25, email='john@example.com')
user.save()
In the example above, we’ve created a new User
instance and called the save
method to insert it into the database.
Querying data
To fetch data from the database, we can use the select
method:
users = User.select()
for user in users:
print(user.name)
In the example above, we’ve selected all users from the User
table and printed their names.
Updating data
To update existing data in the database, we can use the update
method:
user = User.get(User.name == 'John Doe')
user.age = 30
user.save()
In the example above, we’ve fetched the User
with the name ‘John Doe’ and updated the age
field to 30.
Deleting data
To delete data from the database, we can use the delete_instance
method:
user = User.get(User.name == 'John Doe')
user.delete_instance()
In the example above, we’ve fetched the User
with the name ‘John Doe’ and deleted it from the database.
Conclusion
In this blog post, we have explored how to use Peewee with SQLite in Python. We learned how to define models, create tables, insert, query, update, and delete data using Peewee’s expressive API. Peewee simplifies the process of working with databases, making it easier and more intuitive to interact with SQLite and other RDBMS in Python applications.