Peewee 上手

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)載,覺得這篇寫 SQLAlchemy Core,寫得非常不錯。不過后續(xù)他沒寫SQLAlchemy ORM... ...
    非夢nj閱讀 5,499評論 1 14
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,558評論 25 708
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,992評論 19 139
  • 《王六郎》斷背河傳說之五里,我否定了蒲松齡和王觀正一起游般河,拿了宋琬詩題目做證據(jù)。 其實,比較王觀正和蒲松齡的詩...
    覺史氏閱讀 435評論 1 0
  • 我之所有,我之所能,都?xì)w功于我天使般的母親。——林肯 國慶長假期間,廣州南沙區(qū)出現(xiàn)了令人感動的一幕。有位老母親路過...
    悅讀時刻閱讀 742評論 5 3