parameterized insert with Python’s Records

I hate ORMs in general. I also hate SQLAlchemy in particular. It seems like a major flaw in Python’s ecosystem that connection and session handling is so deeply bound to a high magic ORM. (I miss DBI)

Python has Records, which is a nice simple interface. But I couldn’t find anything that explained how to do inserts with it.

This was my first stab at it:

values = {'id':'joy', 'created_at':'Thu Feb 22 18:40:35 +0000 2018'}
insert_sql = "INSERT INTO likes (id, created_at) VALUES (:id, :created_at)"

db.query(insert_sql, values)

This gives an error:

sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'id' [SQL: 'INSERT INTO likes (id, created_at) VALUES (%(id)s, %(created_at)s)'] (Background on this error at: http://sqlalche.me/e/cd3x)

After some fairly frustrating reading the source and Googling, I eventually came up with the following that works

db.query(insert_sql, **values);

Leave a comment