peewee简单使用方法

前记:
之前有使用过python中其他的orm库——sqlalchemy,最近想尝试下peewee,记录一下。

根据已有数据库生成模型

python -m pwiz -e mysql -H 127.0.0.1 -p 3306 -u root -P dbname >model.py
python -m pwiz -e mysql -H {主机地址} -p 3306  -u root -- password   {数据库名称} > {生成的代码文件 例model.py}

其他的使用,建议查看官网文档
参考链接:http://docs.peewee-orm.com/en/latest/

<think>我们被要求使用PythonPeewee库进行ORM操作。根据引用,Peewee是一个轻量级的PythonORM库,支持多种数据库。以下是一个基本的使用指南和示例。首先,确保已经安装了Peewee和对应数据库的驱动(例如,使用MySQL需要安装pymysql):```bashpipinstallpeeweepipinstallpymysql#如果使用MySQL```接下来,我们将通过一个简单的示例来演示Peewee使用。假设我们要创建一个简单的数据库模型来管理用户信息(User),包括用户ID、用户名和电子邮件。###步骤1:连接数据库首先,我们需要建立与数据库的连接。这里以MySQL为例。```pythonfrompeeweeimport*#创建数据库连接db=MySQLDatabase('mydatabase',#数据库名user='myuser',#用户名password='mypassword',#密码host='localhost',#主机port=3306#端口)```###步骤2:定义模型定义一个模型类,每个类对应数据库中的一张表,每个类的字段对应表的列。```pythonclassUser(Model):#CharField对应varchar类型,max_length指定最大长度username=CharField(max_length=50,unique=True)email=CharField(max_length=100)classMeta:database=db#指定数据库table_name='users'#指定表名,可选,默认使用类名的小写```###步骤3:创建表在数据库中创建表。```python#连接数据库db.connect()#创建表,如果表不存在则创建db.create_tables([User])```###步骤4:操作数据####插入数据```python#插入一条数据user1=User(username='john_doe',email='john@example.com')user1.save()#保存到数据库#也可以使用create方法user2=User.create(username='jane_doe',email='jane@example.com')```####查询数据```python#查询所有用户users=User.select()foruserinusers:print(user.username,user.email)#条件查询john=User.get(User.username=='john_doe')print(john.email)#或者使用wherejane=User.select().where(User.username=='jane_doe').get()print(jane.email)```####更新数据```python#更新john的邮箱john.email='john.doe@example.com'john.save()#更新#或者使用update方法query=User.update(email='new_email@example.com').where(User.username=='john_doe')query.execute()```####删除数据```python#删除janejane.delete_instance()#或者使用delete方法query=User.delete().where(User.username=='john_doe')query.execute()```###步骤5:关闭连接```pythondb.close()```###示例总结以上示例展示了Peewee的基本操作:连接数据库、定义模型、创建表以及进行增删改查操作。Peewee还支持更高级的功能,如事务、连接池、复杂查询等,可以参考官方文档进一步学习。§§相关问题§§1.Peewee如何实现多表关联(外键)?2.Peewee中的事务处理是怎样的?3.Peewee支持哪些数据库?如何切换不同的数据库?4.Peewee如何执行原生SQL查询?5.在Peewee中如何进行分页查询?</think>### Python Peewee使用指南 Peewee是一个轻量级Python ORM库,用于简化数据库操作。以下是详细使用示例: #### 1. 安装与数据库连接 ```python pip install peewee pymysql # MySQL示例 ``` ```python from peewee import * # 连接MySQL数据库 db = MySQLDatabase( 'my_database', # 数据库名 user='root', password='secret', host='localhost', port=3306 ) ``` #### 2. 定义数据模型 ```python class User(Model): username = CharField(unique=True) email = CharField() join_date = DateTimeField(default=datetime.now) is_active = BooleanField(default=True) class Meta: database = db # 关联数据库 ``` #### 3. 创建数据表 ```python db.connect() db.create_tables([User]) # 创建表 ``` #### 4. CRUD操作示例 **插入数据**: ```python # 创建单条记录 user = User.create(username='john', email='john@example.com') # 批量插入 users = [ {'username': 'alice', 'email': 'alice@example.com'}, {'username': 'bob', 'email': 'bob@example.com'} ] User.insert_many(users).execute() ``` **查询数据**: ```python # 获取所有用户 all_users = User.select() # 条件查询 active_users = User.select().where(User.is_active == True) # 单条查询 john = User.get(User.username == 'john') ``` **更新数据**: ```python # 更新单条 john.email = 'new_john@example.com' john.save() # 批量更新 query = User.update(is_active=False).where(User.join_date < '2023-01-01') query.execute() ``` **删除数据**: ```python # 删除单条 john.delete_instance() # 批量删除 inactive_users = User.delete().where(User.is_active == False) inactive_users.execute() ``` #### 5. 高级查询 ```python # 排序和限制 users = User.select().order_by(User.join_date.desc()).limit(10) # 聚合查询 user_count = User.select().count() active_count = User.select().where(User.is_active == True).count() # 联表查询 (假设有Post模型) query = (User .select(User, Post) .join(Post, on=(User.id == Post.user_id)) .where(Post.created_at > '2023-06-01')) ``` #### 6. 事务处理 ```python from peewee import transaction with db.atomic() as txn: try: User.create(username='test', email='test@example.com') # 其他操作... except Exception as e: txn.rollback() print("操作失败:", e) ``` [^1][^2][^3]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值