Database

The Peewee Database object represents a connection to a database.The Database class is instantiated with all the information neededto open a connection to a database, and then can be used to:

  • Open and close connections.
  • Execute queries.
  • Manage transactions (and savepoints).
  • Introspect tables, columns, indexes, and constraints.

Peewee comes with support for SQLite, MySQL and Postgres. Each database classprovides some basic, database-specific configuration options.

  1. from peewee import *
  2.  
  3. # SQLite database using WAL journal mode and 64MB cache.
  4. sqlite_db = SqliteDatabase('/path/to/app.db', pragmas={
  5. 'journal_mode': 'wal',
  6. 'cache_size': -1024 * 64})
  7.  
  8. # Connect to a MySQL database on network.
  9. mysql_db = MySQLDatabase('my_app', user='app', password='db_password',
  10. host='10.1.0.8', port=3316)
  11.  
  12. # Connect to a Postgres database.
  13. pg_db = PostgresqlDatabase('my_app', user='postgres', password='secret',
  14. host='10.1.0.9', port=5432)

Peewee provides advanced support for SQLite, Postgres and CockroachDB viadatabase-specific extension modules. To use the extended-functionality, importthe appropriate database-specific module and use the database class provided:

  1. from playhouse.sqlite_ext import SqliteExtDatabase
  2.  
  3. # Use SQLite (will register a REGEXP function and set busy timeout to 3s).
  4. db = SqliteExtDatabase('/path/to/app.db', regexp_function=True, timeout=3,
  5. pragmas={'journal_mode': 'wal'})
  6.  
  7.  
  8. from playhouse.postgres_ext import PostgresqlExtDatabase
  9.  
  10. # Use Postgres (and register hstore extension).
  11. db = PostgresqlExtDatabase('my_app', user='postgres', register_hstore=True)
  12.  
  13.  
  14. from playhouse.cockroachdb import CockroachDatabase
  15.  
  16. # Use CockroachDB.
  17. db = CockroachDatabase('my_app', user='root', port=26257, host='10.1.0.8')

For more information on database extensions, see: