import os #删除数据库 if os.path.exists("people.db"): # 如果文件存在 # 删除文件,可使用以下两种方法。 os.remove("people.db") pass else: print('no such file') # 则返回文件不存在
#TODO 数据库名字 db = SqliteDatabase('people.db') #TODO 创建两张表:Person和Pet class Person(Model): name = CharField() birthday = DateField() class Meta: database = db #指定数据库 class Pet(Model): owner = ForeignKeyField(Person, backref='pets') name = CharField() animal_type = CharField() class Meta: database = db #TODO 连接数据库 db.connect() #TODO 创建两张表Person和Pet db.create_tables([Person, Pet])
#添加数据方式2:: uncle_bob = Person(name='Bob', birthday=date(2020, 1, 1)) uncle_bob.save() # bob is now stored in the database #添加数据方式2: grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1)) herb = Person.create(name='Herb', birthday=date(1950, 5, 5)) herb.save() #用herb.save() 或 grandma.save(),如果都调用,则保存两次
Person.select()
#条件查询 Person.select().where(条件).get uncle_bob = Person.select().where(Person.name == 'Bob').get() print("\nPerson name=Bob Query:") print(uncle_bob.name, uncle_bob.birthday) #条件查询 Person.get(条件) uncle_bob = Person.get(Person.name == 'Bob') print("\nPerson name=Bob Query:") print(uncle_bob.name, uncle_bob.birthday)
grandma=Person.select().where(name = "Grandma") grandma.name = 'Grandma L.' grandma.save()
7.数据删除
herb_mittens = Pet.create(owner=herb, name='Mittens', animal_type='cat') #创建数据 herb_mittens.delete_instance() #删除数据
query = Pet.select().where(Pet.animal_type == 'cat')
#多表查询join--方法1 query = (Pet .select(Pet, Person) .join(Person) .where(Pet.animal_type == 'cat')) #多表查询join--方法2 query = Pet.select().join(Person).where(Person.name == 'Bob')
#升序where(xxx.order_by(yyy)) results = Pet.select().where(Pet.owner == uncle_bob).order_by(Pet.name) #降序where(xxx.order_by(yyy.desc())) results = Pet.select().where(Pet.owner == uncle_bob).order_by(Pet.name.desc())
#查找在1940前和1960后出生的人 d1940 = date(1940, 1, 1) d1960 = date(1960, 1, 1) query = (Person .select() .where((Person.birthday < d1940) | (Person.birthday > d1960))) #查找1940-1960出生的人 query = (Person .select() .where(Person.birthday.between(d1940, d1960)))