请使用python 写一个读写sqlite 的示例程序要求使用orm操作读取指定的表。
下面是一个使用Python的SQLite ORM操作的示例程序:
import sqlite3
from sqlite3 import Error
from peewee import *
# 创建SQLite数据库连接
db = SqliteDatabase('example.db')
# 定义ORM模型类
class Person(Model):
name = CharField()
age = IntegerField()
class Meta:
database = db
# 创建表
Person.create_table()
# 插入数据
person1 = Person(name='Alice', age=25)
person1.save()
person2 = Person(name='Bob', age=30)
person2.save()
# 查询数据
persons = Person.select()
for person in persons:
print(f'Name: {person.name}, Age: {person.age}')
# 更新数据
person1.age = 26
person1.save()
# 删除数据
person2.delete_instance()
# 关闭数据库连接
db.close()
这个示例程序使用了Peewee库作为ORM工具,通过定义一个Person模型类来操作SQLite数据库中的Person表。首先创建了一个SQLite数据库连接,并创建了一个Person表。然后插入了两条数据,查询并输出了所有人员的姓名和年龄。接着对其中一个人的年龄进行了更新,最后删除了另一个人的记录。最后关闭了数据库连接。
你需要先安装Peewee库,可以通过运行pip install peewee来安装
原文地址: https://www.cveoy.top/t/topic/h9HD 著作权归作者所有。请勿转载和采集!