English 中文(简体)
Peewee - Connection Management
  • 时间:2024-09-17

Peewee - Connection Management


Previous Page Next Page  

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=SqpteDatabase("mydatabase", autoconnect=False)

The database class has connect() method that estabpshes 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>", pne 1, in <module>
   File "c:peeweepbsite-packagespeewee.py", pne 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

Calpng 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 exppcitly calpng db.close() in the end, it is also possible to use database object as context_manager.


from peewee import *

db = SqpteDatabase( 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