Peewee 简明教程
Peewee - Connection Management
默认情况下,数据库对象使用 autoconnect 参数设置为 True 创建。相反,为了以编程方式管理数据库连接,它最初被设置为 False。
Database object is created with autoconnect parameter set as True by default. Instead, to manage database connection programmatically, it is initially set to False.
db=SqliteDatabase("mydatabase", autoconnect=False)
数据库类具有 connect() 方法,用于建立与服务器上存在的数据库的连接。
The database class has connect() method that establishes connection with the database present on the server.
db.connect()
强烈建议在完成操作后关闭连接。
It is always recommended to close the connection at the end of operations performed.
db.close()
如果你试图打开一个已经打开的连接,Peewee 会引发 OperationError 。
If you try to open an already open connection, Peewee raises OperationError.
>>> db.connect()
True
>>> db.connect()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\peewee\lib\site-packages\peewee.py", line 3031, in connect
raise OperationalError('Connection already opened.')
peewee.OperationalError: Connection already opened.
要避免此错误,可以使用 reuse_if_open=True 作为 connect() 方法的参数。
To avoid this error, use reuse_if_open=True as argument to connect() method.
>>> db.connect(reuse_if_open=True)
False
在已经关闭的连接上调用 close() 不会导致错误。但是,你可以使用 is_closed() 方法检查连接是否已经关闭。
Calling close() on already closed connection won’t result error. You can however, check if the connection is already closed with is_closed() method.
>>> if db.is_closed()==True:
db.connect()
True
>>>
不必在最后显示调用 db.close()
,你也可以将数据库对象用作 context_manager 。
Instead of explicitly calling db.close() in the end, it is also possible to use database object as context_manager.
from peewee import *
db = SqliteDatabase('mydatabase.db', autoconnect=False)
class User (Model):
user_id=TextField(primary_key=True)
name=TextField()
age=IntegerField()
class Meta:
database=db
db_table='User'
with db:
db.connect()
db.create_tables([User])