Python MySQLDB:在列表中获取fetchall的结果

Rau*_*wal 28 python django mysql-python

我想在列表中获取fetchall操作的结果,而不是元组或元组元组的元组.例如,

cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor
query = "Select id from bs"
cursor.execute(query)
row = cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)

现在,问题是结果行是((123,),(234,))或({'id':123},{'id':234})我要找的是(123,234)或[ 123234].如果我可以保存解析结果集,那就最好了.提前致谢

Cés*_*sar 52

列表理解怎么样?如果结果是((123,), (234,), (345,)):

>>> row = [item[0] for item in cursor.fetchall()]
>>> row
[123, 234, 345]
Run Code Online (Sandbox Code Playgroud)

如果结果是({'id': 123}, {'id': 234}, {'id': 345}):

>>> row = [item['id'] for item in cursor.fetchall()]
>>> row
[123, 234, 345]
Run Code Online (Sandbox Code Playgroud)

  • 老兄我提到过,我试图避免这种情况.我希望光标的编程方式可以直接在列表中获取结果. (8认同)
  • @RaunakAgarwal - 请你是民间的 - 你没有提到你在你的问题中运作的限制,所以有人建议展开嵌套客户端是完全合理的.你应该提到你正在处理数百万行. (6认同)
  • @RaunakAgarwal 也许您可以使用生成器而不是列表推导式。我想它不会那么贵,因为生成器有懒惰的评估 (2认同)

one*_*nch 15

我敢肯定,毕竟这个时候,你却解决了这个问题,对一些人谁可能不知道如何使用MySQLdb的获得光标作为字典的值,你可以用这个方法找到这里:

import MySQLdb as mdb

con = mdb.connect('localhost', 'testuser', 'test623', 'testdb')

with con:

    cur = con.cursor(mdb.cursors.DictCursor)
    cur.execute("SELECT * FROM Writers LIMIT 4")

    rows = cur.fetchall()

    for row in rows:
        print row["Id"], row["Name"]
Run Code Online (Sandbox Code Playgroud)


bil*_*pat 10

在搜索扁平数据库查询时,这个旧Q出现在Google上,所以这里有更多建议...

考虑一个快速列表展平迭代器.

其他答案使用fetchall()首先加载内存中的所有行,然后迭代它以创建一个新列表.可能效率低下.可以与MySQL结合所谓的服务器端游标:

# assume mysql on localhost with db test and table bs
import itertools
import MySQLdb
import MySQLdb.cursors

conn = MySQLdb.connect(host='localhost',db='test', 
          cursorclass=MySQLdb.cursors.SSCursor ) 
cursor = conn.cursor()
# insert a bunch of rows
cursor.executemany('INSERT INTO bs (id) VALUES (%s)',zip(range(1,10000)) )
conn.commit()
# retrieve and listify
cursor.execute("select id from bs")
list_of_ids = list(itertools.chain.from_iterable(cursor))
len(list_of_ids)
#9999
conn.close()
Run Code Online (Sandbox Code Playgroud)

但是这个问题也被标记为Django,它有一个很好的单字段查询flattener

class Bs(models.Model):
    id_field = models.IntegerField()

list_of_ids = Bs.objects.values_list('id_field', flat=True)
Run Code Online (Sandbox Code Playgroud)


小智 5

以这种方式创建光标对象:

db = MySQLdb.connect("IP", "user", "password", "dbname")

cursor = db.cursor(MySQLdb.cursors.DictCursor)
Run Code Online (Sandbox Code Playgroud)

然后,当您对查询执行cursor.fetchall()时,将获得一个字典元组,您可以稍后将其转换为列表。

data = cursor.fetchall()

data = list(data)
Run Code Online (Sandbox Code Playgroud)