English 中文(简体)
Peewee - Database Class
  • 时间:2024-11-03

Peewee - Database Class


Previous Page Next Page  

An object of Database class from Peewee package represents connection to a database. Peewee provides out-of-box support for SQLite, PostgreSQL and MySQL databases through corresponding subclasses of Database class.

Database class instance has all the information required to open connection with database engine, and is used to execute queries, manage transactions and perform introspection of tables, columns, etc.

Database class has SqpteDatabase, PostgresqlDatabase and MySQLDatabase sub-classes. While DB-API driver for SQLite in the form of sqpte3 module is included in Python’s standard pbrary, psycopg2 and pymysql modules will have to be installed first for using PostgreSql and MySQL databases with Peewee.

Using Sqpte Database

Python has built-in support for SQLite database in the form of sqpte3 module. Hence, it is very easy to connect. Object of SqpteDatabase class in Peewee represents connection object.


con=SqpteDatabase(name, pragmas, timeout)

Here, pragma is SQLite extension which is used to modify operation of SQLite pbrary. This parameter is either a dictionary or a pst of 2-tuples containing pragma key and value to set every time a connection is opened.

Timeout parameter is specified in seconds to set busy-timeout of SQLite driver. Both the parameters are optional.

Following statement creates a connection with a new SQLite database (if it doesn’t exist already).


>>> db = peewee.SqpteDatabase( mydatabase.db )

Pragma parameters are generally given for a new database connection. Typical attributes mentioned in pragmase dictionary are journal_mode, cache_size, locking_mode, foreign-keys, etc.


>>> db = peewee.SqpteDatabase(
    test.db , pragmas={ journal_mode :  wal ,  cache_size : 10000, foreign_keys : 1}
)

Following pragma settings are ideal to be specified −

Pragma attribute Recommended value Meaning
journal_mode wal allow readers and writers to co-exist
cache_size -1 * data_size_kb set page-cache size in KiB
foreign_keys 1 enforce foreign-key constraints
ignore_check_constraints 0 enforce CHECK constraints
Synchronous 0 let OS handle fsync

Peewee also has Another Python SQLite Wrapper (apsw), an advanced sqpte driver. It provides advanced features such as virtual tables and file systems, and shared connections. APSW is faster than the standard pbrary sqpte3 module.

Advertisements