[파이썬] Peewee 테이블 생성 및 삭제

Peewee is a lightweight and expressive Object Relational Mapping (ORM) library for Python. It provides a simple and intuitive way to interact with databases, allowing you to easily create, manipulate, and delete tables. In this blog post, we will explore how to create and delete tables using Peewee.

Installation

Before we start, let’s make sure we have Peewee installed. You can install it using pip:

pip install peewee

Creating a Table

To create a table in Peewee, we need to define a Python class that inherits from peewee.Model and represents the table schema. Each attribute in the class represents a column in the table. Let’s say we want to create a table called “users” with the following columns: “id”, “name”, and “email”. Here’s an example of how we can define the table:

from peewee import *

# Create a database connection
db = SqliteDatabase('my_database.db')

# Define the model representing the table
class User(Model):
    id = AutoField()
    name = CharField()
    email = CharField()

    class Meta:
        database = db

# Create the table
db.connect()
db.create_tables([User])
db.close()

In the above example, we first import the necessary classes from Peewee. Then, we define our model class User which represents the “user” table. We define three columns: id as an AutoField (auto-incrementing primary key), name as a CharField, and email as a CharField.

Finally, we create an instance of the database, connect to it, create the table, and close the connection.

Deleting a Table

To delete a table in Peewee, we can use the drop_table() method in the database object. Let’s say we want to delete the “users” table. Here’s an example:

from peewee import *

# Create a database connection
db = SqliteDatabase('my_database.db')

# Define the model representing the table
class User(Model):
    id = AutoField()
    name = CharField()
    email = CharField()

    class Meta:
        database = db

# Delete the table
db.connect()
db.drop_table(User)
db.close()

In the above example, we first import the necessary classes from Peewee. Then, we define our model class User which represents the “user” table (similar to the previous example).

Finally, we create an instance of the database, connect to it, delete the table using the drop_table() method, and close the connection.

Conclusion

Peewee makes it easy to create and delete tables in Python. By defining a Python class representing the table schema and using Peewee’s database connection methods, we can effortlessly create and delete tables. So go ahead and start exploring the power of Peewee ORM in your Python projects!