3. Database

from skylark import Database

or:

from skylark import database  # alias of `Database`

3.1. Set A DBAPI

Skylark currently supports 3 DBAPI(db connectors):

Skylark will try to load them in this order: MySQLdb, pymysql, sqlite3, and use the connector found, to explicitly tell skylark to use a connector:

import pymysql
Database.set_dbapi(pymysql)

3.2. DB configuration

It depends on your connector.

3.2.1. MySQLdb & PyMySQL

For mysql, all available configuration items are here.

An example:

Database.config(db='mydb', user='root', passwd='', charset='utf8')

3.2.2. Sqlite3

Database.config(db='mydb')

3.3. Autocommit

By default, autocommit mode is on, to set this mode:

Database.set_autocommit(boolean)

3.4. Transaction

Transaction is supported since v0.9.0.

An example:

with Database.transaction():
    User.create(name='jack', email='jack@gmail.com')

We can run a lot of insert queries within a transaction.

Another example:

t = Database.transaction()

try:
    User.create(..)   # run queries
except:
    t.rollback()
else:
    t.commit()

3.5. Change DB

To select another database:

Database.change(db)

or:

Database.select_db(db)  # alias of `change`

3.6. Execute Raw Query

If you are dealing tasks outside of skylark’s abilities, and need to run a raw query:

Database.execute(sql, params)