I have some code which I’ve been using to query MySQL, and I’m hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn’t work with SQLite:
cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data.append(row['column_name'])
This gives the following error:
TypeError: tuple indices must be integers
Whereas if I change the reference to use a column number, it works fine:
data.append(row[1])
Can I execute the query in such a way that I can reference columns by their names?
I’m not sure if this is the best approach, but here’s what I typically do to retrieve a record set using a DB-API 2 compliant module:
The query formatting method is one of the DB-API standards, but happens to be the preferred method for Psycopg2; other DB-API adapters might suggest a different convention which will be fine.
Writing queries like this, where implicit tuple unpacking is used to work with the result set, has typically been more effective for me than trying to worry about matching Python variable names to SQL column names (which I usually only use to drop prefixes, and then only if I’m working with a subset of the column names such that the prefixes don’t help to clarify things anymore), and is much better than remembering numerical column IDs.
This style also helps you avoid
SELECT * FROM table..., which is just a maintenance disaster for anything but the simplest tables and queries.So, not exactly the answer you were asking for, but possibly enlightening nonetheless.