开发者

Why is recordset result being returned in this way for Python database query?

开发者 https://www.devze.com 2022-12-28 03:43 出处:网络
I have searched high and low for an answer to why query results return开发者_JAVA技巧ed in this format and how to convert to a list.

I have searched high and low for an answer to why query results return开发者_JAVA技巧ed in this format and how to convert to a list.

data = cursor.fetchall()

When I print data, it results in: (('car',), ('boat',), ('plane',), ('truck',))

I want to have the results in a list as ["car", "boat", "plane", "truck"]


It's returning it in that way because a recordset is comprised of many rows of data, not a list of single elements.

You can flatten it if you want using a list comprehension:

data = [row[0] for row in cursor.fetchall()]


The result for fetchall() returns an array of rows, where each row is an array with one value per column.

Even if you are selecting only one column, you will still get an array of arrays, but only one value for each row.


x = (('car',), ('boat',), ('plane',), ('truck',))

y = [z[0] for z in x] # ['car', 'boat', 'plane', 'truck']
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号