Peewee - Connection Management



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)

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()

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.

To avoid this error, use reuse_if_open=True as argument to connect() method.

>>> db.connect(reuse_if_open=True)
False

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
>>>

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])
Advertisements