coderholic

EasyDB: Simple SQL Persistence for Python

Python provides some great tools for simple data persistence. For key value storage there's anydb for when you have only string values, and shelve for when you've got more complex values (eg. lists or objects).

Sometimes key value persistence doesn't cut it. For example, you might want to sort, filter or query your data efficiently. In those situations you can always use Python's built in support for SQLite - a serverless self-contained SQL database engine. With SQLite you've got to worry about database schemas, connections and transactions though. A far cry from simple persistence!

Enter EasyDB - essentially a really simple SQLite wrapper for that saves you from having to worry about creating tables, managing connections or transactions. Here's a quick example:

from easydb import EasyDB
db = EasyDB('filename.db', {'users': ['username text', 'comments text']})

db.query("INSERT INTO users (username, comments) VALUES (?, ?)", ('ben', 'Python coder'))

for result in db.query("SELECT * FROM users"):
    print result
    
# => ('ben', 'Python coder')

If the filename being passed into the EasyDB constructor already exists it'll get reused. Otherwise it'll be created with the provided database structure. Notice that you don't need to worry about the correct SQL syntax for creating tables, you just provide the details as a Python dictionary in the following format (see the SQLite documentation for a list of available types):

{
    'table_name': ['column_name column_type', '…'],
    'table_name': ['column_name column_type', '…'],
}

EasyDB can also be used on existing SQLite database by simply passing in the database filename:

from easydb import EasyDB
db = EasyDB('filename.db')
results = db.query("SELECT * FROM mytable").fetchall()

EasyDB is available on GitHub at https://github.com/coderholic/easydb, and can also be installed via pip.

Posted on 10 Mar 2012
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.