我已经实现了以下代码:
from peewee import Model, MySQLDatabase, CharField
from contextlib import contextmanager
@contextmanager
def get_database():
return MySQLDatabase("films", user="root", host="localhost", port=3306)
class BasePeeweeModel(Model):
class Meta: database = db
class Films(BasePeeWeeModel):
code = CharField()
name = CharField()
try:
db.create_tables([Films])
except OperationalError:
print "Films able already exists"
with get_database() as db:
fobj = Films()
fobj.code = "LJ"
fobj.name = "Le Jatte"
fobj.save()
我希望能够在完成表任务后显式关闭数据库连接!