Database binding

The database object has the Database.bind() method. It is used for attaching declared entities to a specific database. If you want to play with Pony in the interactive mode, you can use the SQLite database created in memory:

  1. >>> db.bind(provider='sqlite', filename=':memory:')

Currently Pony supports 5 database types: 'sqlite', 'mysql', 'postgresql', 'cockroach' and 'oracle'. The subsequent parameters are specific to each database. They are the same ones that you would use if you were connecting to the database through the DB-API module.

For SQLite, either the database filename or the string ‘:memory:’ must be specified as the parameter, depending on where the database is being created. If the database is created in-memory, it will be deleted once the interactive session in Python is over. In order to work with the database stored in a file, you can replace the previous line with the following:

  1. >>> db.bind(provider='sqlite', filename='database.sqlite', create_db=True)

In this case, if the database file does not exist, it will be created. In our example, we can use a database created in-memory.

If you’re using another database, you need to have the specific database adapter installed. For PostgreSQL Pony uses psycopg2. For MySQL either MySQLdb or pymysql adapter. For Oracle Pony uses the cx_Oracle adapter.

Here is how you can get connected to the databases:

  1. # SQLite
  2. db.bind(provider='sqlite', filename=':memory:')
  3. # or
  4. db.bind(provider='sqlite', filename='database.sqlite', create_db=True)
  5. # PostgreSQL
  6. db.bind(provider='postgres', user='', password='', host='', database='')
  7. # MySQL
  8. db.bind(provider='mysql', host='', user='', passwd='', db='')
  9. # Oracle
  10. db.bind(provider='oracle', user='', password='', dsn='')
  11. # CockroachDB
  12. db.bind(provider='cockroach', user='', password='', host='', database='', )