Tuesday, March 16, 2010

Select Records Instead of Arrays

Earlier versions of the SQLForce Jython module support SELECT statements like:
session = SQLForce.Session("sandbox")
for row in session.select( "SELECT id, FirstName, LastName FROM Contact LIMIT 3"):
    print "First Name: " + row[1]
    print "Last Name: " + row[2] 
This works OK as long as each row is referenced in close proximity to the session.select() and not many columns are being selected.

When selecting a lot of columns, I found this technique to be error prone...so I introduced a form of select, session.selectRecords() that returns jython classes where the class attributes are set to the name of each column. Example:

session = SQLForce.Session("sandbox")
for row in session.selectRecords( "SELECT id, name, account.name FROM Contact LIMIT 3"):
    print "Name: " + row.name
    print "Account: " + row.account.name
The only trick to to use the same column name referenced in the SELECT statement. Naturally, a session.selectRecords2(sql, callback) form is also supplied.

That's it..a small change that makes code more readable.