附录2:调用示例
from peewee import *
import datetime
from datetime impotr date
import logging
#输出SQL日志
#logger = logging.getLogger('peewee')
#logger.addHandler(logging.StreamHandler())
#logger.setLevel(logging.DEBUG)
#新建数据库db
db = PostgresqlDatabase('test',host='127.0.0.1',port=5432,
user='vbadmin',password='password')
db.connect()
class Person(Model):
name = CharField(index=False,column_name='name1')
birthday = DateField()
is_relative = BooleanField()
class Meta:
database = db
def create_p():
#创建表
Person.create_table()
#创建多个,可以在[]中写多个表名
#database.create_tables([Person])
def insert_p():
#添加一条数据
p = Person(name='lcg', birthday=date(1990,12,20), is_relative=True)
p.save()
#直接create,create之后还会返回创建的这条数据,方便进行其他操作
p = Person.create(name='yyy', birthday=date(2004,2,7), is_relative=False)
#使用属性作为参数
p = Person.insert(name='zzz', birthday=date(2001,12,2), is_relative=False)
.execute()
#使用列属性和值映射
Person.insert({
Person.name: 'meow',
Person.birthday: datetime.datetime.now(),
Person.is_relative: True}).execute()
def update_p():
query = Person.update(is_relative=True).where(Person.name =='zzz')
query.execute()
def select_p():
#get的括号中给定条件,可以一次性多个条件
people = Person.get(Person.name == 'yyy', Person.is_relative == False)
print(people.name)
#保留is_relative的名字
people = Person.select(Person.name).where(Person.is_relative == True)
for i in people:
print(i.name)
def delete_p():
#删除所有在18年前出生的人的信息,返回删除个数
n = Person.delete().where(Person.birthday < datetime.date(2000,1,1))
.execute()
#获取is_relative=False的人的id
people = Person.select(Person.id).where(Person.is_relative == False)
#删除前面获取到的ID的信息
Person.delete().where(Person.id.in_(people)).execute()
def drop_p():
db.drop_tables([Person])
create_p()
insert_p()
update_p()
select_p()
delete_p()
drop_p()