peewee是python編寫的ORM,ORM是一種程序技術(shù),用于實現(xiàn)面向?qū)ο缶幊陶Z言里不同類型系統(tǒng)的數(shù)據(jù)之間的轉(zhuǎn)換,從效果上說,它其實是創(chuàng)建了一個可在編程語言里使用的--“虛擬對象數(shù)據(jù)庫”,意思就是通過程序語言操作數(shù)據(jù)庫。
peewee提供多種數(shù)據(jù)庫的使用,Sqlite、MySQL、Postgresql。
這里以mysql為例子,介紹一些基本用法。
創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE test
DEFAULT CHARSET utf8
COLLATE UTF8_GENERAL_Ci;
連接數(shù)據(jù)庫
from peewee import MySQLDatabase, Model, CharField
db = MySQLDatabase(
host='127.0.0.1',
user='root',
passwd='root',
database='test',
port=3306
)
db.connect()
數(shù)據(jù)操作
- 建立表
class Student(Model):
stu_num = CharField()
name = CharField()
stu_class = CharField()
class Meta:
database = db
db.create_table(Student)
# 也可同時建立多個表
db.create_tables([table1, table2, ...])
- 保存數(shù)據(jù)
# 第一種
stu = Student(stu_num='test', name='kirito', stu_class='三年二班')
stu.save()
# 第二種
Student.create(stu_num='test', name='kirito', stu_class='三年二班')
- 讀取數(shù)據(jù)
讀取所有數(shù)據(jù)
for stu in Student.select():
print('{}\n{}\n{}\n'.format(
stu.stu_num, stu.name, stu.stu_class))
篩選數(shù)據(jù)
stu = Student.select().where(Student.name == 'kirito').get()
print(stu.name)
更新數(shù)據(jù)
stu.name == 'leo'
stu.save()
刪除數(shù)據(jù)
herb_mittens.delete_instance()
- 外鍵查詢
建立一個和student關(guān)聯(lián)的表
class Book(Model):
book_name = CharField(max_length=50)
belong_to = ForeignKeyField(Student, related_name='books')
class Meta:
database = db
通過student查詢屬于他的所有book, 這里有兩種方法,第二種要好
兩次for循環(huán)
for stu in Student.select():
for book in stu.books:
print(book.book_name)
一次for循環(huán)
query = (Book.select(Book, Student).join(Student))
for book in query:
print(book.book_name)