lundi 14 septembre 2015

Generalizing sqlalchemy statements

Let us say that we have a table in a SQLite database named abcd which looks like the following:

| head1 | head2 | head3 | |-------|-------|-------| | a | b | Null |

Here Null represents a value not present. Now we want to update the Null value in head3. CUrrently I am using sqlalchemy.

One way of updating the column is the following:

import sqlalchemy as sql
db       = sql.create_engine('sqlite:///%s'%dbName) # dbName isnt important
meta     = sql.MetaData(db)
meta.reflect(db)
conn     = db.connect()

table = meta.tables['abcd']

update = table.update()
update = update.where( table.c['head2'] == 'b' )
update = update.values( head3 = 'test' )
result = conn.execute( update )
result.close()

Now we want to generalize the function. We want to put this entire segment in a function. That means that all the variables, 'dbName', 'abcd', 'head2', and 'head3' should be inputs to the function. All this is well and fine, except the one statement

update = update.values( head3 = 'test' )

Here, I would like to do something like:

tempColName = table.c['head3']
update = update.values( tempColName = 'test' )

However, this is where the problem occurs. We can't do this in this way, because the values() function expects this value to the actual name of the table. Is there any way in which we can do this?

Aucun commentaire:

Enregistrer un commentaire