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.
- from peewee import *
- # SQLite database using WAL journal mode and 64MB cache.
- sqlite_db = SqliteDatabase('/path/to/app.db', pragmas={
- 'journal_mode': 'wal',
- 'cache_size': -1024 * 64})
- # Connect to a MySQL database on network.
- mysql_db = MySQLDatabase('my_app', user='app', password='db_password',
- host='10.1.0.8', port=3316)
- # Connect to a Postgres database.
- pg_db = PostgresqlDatabase('my_app', user='postgres', password='secret',
- 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:
- from playhouse.sqlite_ext import SqliteExtDatabase
- # Use SQLite (will register a REGEXP function and set busy timeout to 3s).
- db = SqliteExtDatabase('/path/to/app.db', regexp_function=True, timeout=3,
- pragmas={'journal_mode': 'wal'})
- from playhouse.postgres_ext import PostgresqlExtDatabase
- # Use Postgres (and register hstore extension).
- db = PostgresqlExtDatabase('my_app', user='postgres', register_hstore=True)
- from playhouse.cockroachdb import CockroachDatabase
- # Use CockroachDB.
- db = CockroachDatabase('my_app', user='root', port=26257, host='10.1.0.8')
For more information on database extensions, see:
- Postgresql Extensions
- SQLite Extensions
- Cockroach Database
- Sqlcipher backend (encrypted SQLite database).
- apsw, an advanced sqlite driver
- SqliteQ