Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

sqlite - Get a list of field values from Python's sqlite3, not tuples representing rows

It's annoying how Python's sqlite3 module always returns a list of tuples! When I am querying a single column, I would prefer to get a plain list.

e.g. when I execute

SELECT somecol FROM sometable

and call

cursor.fetchall()

it returns

[(u'one',), (u'two',), (u'three',)]

but I'd rather just get

[u'one', u'two', u'three']

Is there a way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

sqlite3.Connection has a row_factory attribute.

The documentation states that:

You can change this attribute to a callable that accepts the cursor and the original row as a tuple and will return the real result row. This way, you can implement more advanced ways of returning results, such as returning an object that can also access columns by name.

To return a list of single values from a SELECT, such as an id, you can assign a lambda to row_factory which returns the first indexed value in each row; e.g:

import sqlite3 as db

conn = db.connect('my.db')
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()
ids = c.execute('SELECT id FROM users').fetchall()

This yields something like:

[1, 2, 3, 4, 5, 6] # etc.

You can also set the row_factory directly on the cursor object itself. Indeed, if you do not set the row_factory on the connection before you create the cursor, you must set the row_factory on the cursor:

c = conn.cursor()
c.row_factory = lambda cursor, row: {'foo': row[0]}

You may redefine the row_factory at any point during the lifetime of the cursor object, and you can unset the row factory with None to return default tuple-based results:

c.row_factory = None
c.execute('SELECT id FROM users').fetchall() # [(1,), (2,), (3,)] etc.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...