简体   繁体   中英

How do I select a column by its name? (Python & SQLite3)

Currently I have the following code:

c.execute("SELECT * FROM table")
for row in c.fetchall():
    print row[0]
    print row[1]

However, I changed the structure of my table and now I have to change the index values to represent this change. Is there a way to get use column names instead?

For this reason, it is recommended to always use explicit column names when doing a SELECT :

c.execute("SELECT color, fluffiness FROM table")
for row in c.fetchall():
    print row[0]         #  <-- is always guaranteed to be the color value
    print row[1]

See Row Objects in the docs for the sqlite3 module. If you use the sqlite3.Row row_factory you'll get back an object that's slightly more powerful than the normal tuples. I imagine it has slightly higher overhead, hence not being the default behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM