Binding the database object to a specific database
Before we can map entities to the database, we need to connect to establish connection to it. It can be done using the bind()
method:
db.bind(provider='postgres', user='', password='', host='', database='')
The first parameter of this method is the name of the database provider. The database provider is a module which resides in the pony.orm.dbproviders
package and which knows how to work with a particular database. After the database provider name you should specify parameters which will be passed to the connect()
method of the corresponding DBAPI driver.
Currently Pony can work with the following database systems: SQLite, PostgreSQL, MySQL, Oracle, CockroachDB, with the corresponding Pony provider names: 'sqlite'
, 'postgres'
, 'mysql'
, 'oracle'
and 'cockroach'
. Pony can easily be extended to incorporate additional database providers.
When you just start working with Pony, you can use the SQLite database. This database is included into Python distribution and you don’t need to install anything separately. Using SQLite you can create the database either in a file or in memory. For creating the database in the file use the following command:
db.bind(provider='sqlite', filename='database.sqlite', create_db=True)
When create_db=True
, Pony will create the database file if it doesn’t exist. If it already exists, Pony will use it.
For in-memory database use this:
db.bind(provider='sqlite', filename=':memory:')
There is no need in the parameter create_db
when creating an in-memory database. This is a convenient way to create a SQLite database when playing with Pony in the interactive shell, but you should remember, that the entire in-memory database will be lost on program exit.
Here are the examples of binding to other databases:
db.bind(provider='sqlite', filename=':memory:')
db.bind(provider='sqlite', filename='filename', create_db=True)
db.bind(provider='mysql', host='', user='', passwd='', db='')
db.bind(provider='oracle', user='', password='', dsn='')
db.bind(provider='cockroach', user='', password='', host='',
database='', sslmode='disable')
You can find more details on working with each database in the API Reference: