Peewee and SQLite User Database Creation with Peewee

  • Share this:

Code introduction


This code defines a database model using Peewee and SQLite, which creates a database table for user information and inserts a new user record.


Technology Stack : Peewee, SQLite

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from peewee import *

def create_user_table():
    # Define a database connection using SQLite
    database = SqliteDatabase('users.db')

    # Define a base class for all models that will use this database
    class BaseModel(Model):
        class Meta:
            database = database

    # Define a User model
    class User(BaseModel):
        username = CharField()
        email = CharField()
        password = CharField()

    # Connect to the database and create tables
    database.connect()
    database.create_tables([User])

    # Insert a new user
    new_user = User(username='john_doe', email='john@example.com', password='securepassword')
    new_user.save()

    # Close the database connection
    database.close()

# JSON representation of the code                
              
Tags: