Creating Database and User Table with SQLAlchemy

  • Share this:

Code introduction


Create a new database and a user table if they do not exist.


Technology Stack : SQLAlchemy, SQLAlchemy-Utils

Code Type : Function

Code Difficulty : Intermediate


                
                    
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_utils import database_exists, create_database

# Define the base class
Base = declarative_base()

# Define a simple model
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

# Function to create a new database and table if they do not exist
def create_user_table(engine):
    if not database_exists(engine.url):
        create_database(engine.url)
    Base.metadata.create_all(engine)

# JSON object with information about the function
info = {
    "type": "Function",
    "hard": "中级",
    "explain": "创建一个新数据库和一个用户表(如果它们不存在的话)。",
    "tench": "SQLAlchemy, SQLAlchemy-Utils",
    "explain_en": "Create a new database and a user table if they do not exist.",
    "tench_en": "SQLAlchemy, SQLAlchemy-Utils"
}

# Function definition
def xxx(engine):
    create_user_table(engine)