Peewee 是一个功能强大且灵活的 Python ORM(对象关系映射)库,它支持多种常见的数据库,以下为你详细介绍:
1. SQLite
特点:轻量级、零配置、文件型数据库,非常适合小型项目、测试环境或者嵌入式系统。它不需要单独的服务器进程,数据以文件形式存储在本地。
使用示例
from peewee import *
# 连接 SQLite 数据库
db = SqliteDatabase('test.db')
class BaseModel(Model):
class Meta:
database = db
class Book(BaseModel):
title = CharField()
# 创建表
db.create_tables([Book])
2. MySQL
特点:开源、高性能、广泛使用的关系型数据库,具有良好的扩展性和稳定性,适用于各种规模的项目,尤其是 Web 应用。
使用示例
from peewee import *
# 连接 MySQL 数据库
db = MySQLDatabase('your_database_name', user='your_username', password='your_password',
host='localhost', port=3306)
class BaseModel(Model):
class Meta:
database = db
class Product(BaseModel):
name = CharField()
# 创建表
db.create_tables([Product])
3. PostgreSQL
特点:功能强大、开源的对象 - 关系型数据库管理系统,支持高级数据类型、复杂查询和事务处理,具有高度的可定制性和可靠性,常用于企业级应用。
使用示例
from peewee import *
# 连接 PostgreSQL 数据库
db = PostgresqlDatabase('your_database_name', user='your_username', password='your_password',
host='localhost', port=5432)
class BaseModel(Model):
class Meta:
database = db
class Employee(BaseModel):
name = CharField()
# 创建表
db.create_tables([Employee])
4. CockroachDB
特点:分布式 SQL 数据库,具有强一致性、高可用性和水平扩展性,适用于需要处理大规模数据和高并发访问的场景。
使用示例:与 PostgreSQL 连接方式类似,因为 CockroachDB 兼容 PostgreSQL 协议。
from peewee import *
# 连接 CockroachDB 数据库
db = PostgresqlDatabase('your_database_name', user='your_username', password='your_password',
host='localhost', port=26257)
class BaseModel(Model):
class Meta:
database = db
class Order(BaseModel):
order_number = CharField()
# 创建表
db.create_tables([Order])
5. Oracle
特点:商业数据库,具有强大的功能、高可靠性和安全性,广泛应用于大型企业级应用和数据仓库。
使用示例:需要安装
cx_Oracle
驱动。
import cx_Oracle
from peewee import *
# 连接 Oracle 数据库
dsn = cx_Oracle.makedsn('localhost', 1521, service_name='your_service_name')
db = OracleDatabase('your_username/your_password@' + dsn)
class BaseModel(Model):
class Meta:
database = db
class Customer(BaseModel):
name = CharField()
# 创建表
db.create_tables([Customer])
6. Microsoft SQL Server
特点:微软开发的关系型数据库管理系统,与 Windows 操作系统集成良好,提供了丰富的工具和功能,适用于企业级应用开发。
使用示例:需要安装
pymssql
驱动。
from peewee import *
# 连接 SQL Server 数据库
db = MySQLDatabase('your_database_name', user='your_username', password='your_password',
host='localhost', port=1433)
class BaseModel(Model):
class Meta:
database = db
class Invoice(BaseModel):
invoice_number = CharField()
# 创建表
db.create_tables([Invoice])
除了上述数据库,Peewee 还支持通过扩展和自定义来适配其他数据库,你可以根据项目的需求选择合适的数据库。