归类 : Python
文集 : Python杂记

peewee是一款轻量级、丰富的ORM(Object Relation Mapping,对象关系映射)

创建数据库

    # sqllite
    db = SqliteDatabase('person.db')
    class Person(Model):
        name = CharField(max_length=50)  # varchar(50)
        age = IntegerField()  # int
        birthday = DateTimeField()  # 时间格式
        class Meta:
            database = db  # 数据库
            db_table = 's_person'  # 表名
    
    class Home(Model):
        owner = ForeignKeyField(Person, backref='home')
        address = CharField()
        class Meta:
            database = db  # 数据库
            db_table = 's_home'  # 表名
    
    if __name__ == '__main__':
        db.connect()
        db.create_tables([Home, Person])

创建表

    db.create_tables([Home, Person])

使用save()、execute()或create()方法来添加和更新表

    p1=Person()
    p1.name='a'
    p1.age=20
    p1.birthday=datetime.datetime.now()
    p1.save()
    #或
    p2=Person(name='b',age='30',birthday=datetime.datetime.now())
    p2.save()
    #或
    p3=Person().insert(name='c',age='30',birthday=datetime.datetime.now())
    p3.execute()
    #或
    p4=Person.create(name='d',age='30',birthday=datetime.datetime.now())

    p=Person.delete().where(Person.name=='d')
    p.execute()
    #或
    p=Person.get(name='c')
    p.delete_instance()

    p=Person.update(age=100).where(Person.name=='a')
    p.execute()
    #或
    p=Person().get(name='b')
    p.age=101
    p.save()

查询所有

    p_list=Person.select()

查多条

    p_list=Person.select().where(Teacher.age==30)

查单条

    p=Person.select().where(Teacher.name=='a').get()
    #或
    p=Person.get(Teacher.name=='a')

排序

升序

    p_list=Person.select().order_by(Person.name)

降序


    p_list=Person.select().order_by(Person.name.desc)

使用sql查询

    sql = "select * from s_person where name = 'a' and age = 30"
    p_list=Person.raw(sql)

以上