Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python sqlmodel

作者:妖孽少年   发布日期:2025-11-09   浏览:25

from sqlmodel import SQLModel, Field, create_engine, Session, select

# 定义一个SQLModel类,对应数据库中的表
class Hero(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: int | None = None

# 创建SQLite数据库引擎
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)

# 创建表结构(如果表不存在的话)
def create_db_and_tables():
    SQLModel.metadata.create_all(engine)

# 添加数据到数据库
def create_heroes():
    hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
    hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
    hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)

    with Session(engine) as session:
        session.add(hero_1)
        session.add(hero_2)
        session.add(hero_3)
        session.commit()

# 查询数据
def select_heroes():
    with Session(engine) as session:
        statement = select(Hero)
        results = session.exec(statement)
        for hero in results:
            print(hero)

if __name__ == "__main__":
    create_db_and_tables()
    create_heroes()
    select_heroes()

解释说明:

  1. 导入模块:从 sqlmodel 模块中导入所需的类和函数。
  2. 定义模型类:创建一个名为 Hero 的类,继承自 SQLModel,并设置为表格。类中的字段对应数据库表的列。
  3. 创建数据库引擎:使用 SQLite 数据库,并创建一个连接引擎。
  4. 创建表结构:通过 create_db_and_tables 函数检查并创建数据库中的表。
  5. 添加数据:通过 create_heroes 函数向数据库中插入几条记录。
  6. 查询数据:通过 select_heroes 函数查询并打印所有英雄的数据。

这个示例展示了如何使用 SQLModel 来创建、插入和查询数据。

上一篇:python 发送http请求

下一篇:python fstring

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站