User Tools

Site Tools


SQL Alchemy + MySQL + SqlSoup


For this I'll be using ipython (Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) and SQLAlchemy version 0.6 (with mysql-python ).
We assume that we already have created a 'test' database with a table 'users' in it (for the table structure see below)
Because we're dealing with already existing data, we'll be using SqlSoup , which is a convenient way to access existing database tables without having to declare table or mapper classes ahead of time. It is built on top of the SQLAlchemy ORM and provides a super-minimalistic interface to an existing database.

Create the connection

from sqlalchemy.ext.sqlsoup import SqlSoup
db = SqlSoup('mysql+mysqldb://root:password@localhost/test?charset=utf8')
# or db = SqlSoup(engine) if you have engine previously defined

Load our existing table

users_tbl = db.users
In [73]: type(users_tbl)
Out[73]: <class 'sqlalchemy.ext.sqlsoup.TableClassType'>


First, get all users (we have just two there at this time):

In [17]: [ (,,user.age) for user in users_tbl.all() ]
Out[17]: [(1L, u'John Doe', 34), (2L, u'Tom Bruise', 23)]

Get after primary key (in this case called id)

In [21]: users_tbl.get(2)
Out[21]: MappedUsers(id=2L,name=u'Tom Bruise',age=23)

Filter after some conditions:

- after name only (using filter_by)

In [41]: users_tbl.filter_by(name='Tom Bruise').one()
Out[41]: MappedUsers(id=2L,name=u'Tom Bruise',age=23)

- after name only (using filter and LIKE)

In [57]: users_tbl.filter("Tom%")).one()
Out[57]: MappedUsers(id=2L,name=u'Tom Bruise',age=23)

- after name and age (using filter, or_, and_)

from sqlalchemy import or_, and_, desc
whereRule = and_('Tom Bruise', users_tbl.age==23)
In [44]: users_tbl.filter(whereRule).all()
Out[44]: [MappedUsers(id=2L,name=u'Tom Bruise',age=23)]

- after name (using IN)

In [62]: users_tbl.filter(['Tom Bruise', 'Bruce Lee', 'John Doe'])).all()
[MappedUsers(id=1L,name=u'John Doe',age=34),
 MappedUsers(id=2L,name=u'Tom Bruise',age=23)]

Modifying objects

eduser = users_tbl.get(2) # grab the user
eduser.age = 12 # modify age
db.commit() # save

Insert new objects

In [70]: users_tbl.insert(name="Ronnie James Dio", age=54)
Out[70]: MappedUsers(id=None,name='Ronnie James Dio',age=54)
In [71]: db.commit()  # actually commits the data

Delete data

deluser = users_tbl.get(2) # grab the user using primary key or any other method (filter, filter_by, etc)


python/sqlalchemymysql.txt · Last modified: 2013/03/16 17:40 (external edit)