SimpleDB: python MySQLdb wrapper with auto connect

You may get the simpledb.py module source on google code.

Usage:

Create SimpleDB object and connect to database

Note: you must have MySQLdb module installed first.

import simpledb
db = simpledb.SimpleDB(host='localhost', user='test_user', password='test_password', db_name='test')

Select one row from db as a list

>>> db.get_one('SELECT * FROM users')
(1L, u'bill gates')

Select one row from db as dict

>>> db.get_one_dict('SELECT * FROM users')
{'user_name': u'bill gates', 'id': 1L}

Select all row from db as a list of rows in list

>>> db.get_all('SELECT * FROM users')
((1L, u'bill gates'), (2L, u'linus torvalds'))

Select all row from db as a list of rows in dict

>>> db.get_all_dict('SELECT * FROM users')
({'user_name': u'bill gates', 'id': 1L}, {'user_name': u'linus torvalds', 'id': 2L})

execute update/insert statement which does not return result set, commit changes to database

>>> db.execute_sql('INSERT INTO users(user_name) VALUES(%s)', 'Dennis Ritchie')
>>> db.get_all('SELECT * FROM users')
((1L, u'bill gates'), (2L, u'linus torvalds'), (3L, u'Dennis Ritchie'))

Note: if you don’t want to commit SQL, eg. you want to use transaction, you may use the execute_sql_no_commit function:

db.exuecte_sql_no_commit('START TRANSACTION')
db.exuecte_sql_no_commit('xxx...')
db.exuecte_sql_no_commit('yyy...')
db.commit()

Note, the auto re-connection is performed behind the scenes: If a DB operation failed, it will try to reconnect to the DB and then execute the same operation once again.

This entry was posted in Programming, Python and tagged . Bookmark the permalink.

Leave a Reply