我想在列表中获取fetchall操作的结果,而不是元组或元组元组的元组。 例如,
cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor
query = "Select id from bs"
cursor.execute(query)
row = cursor.fetchall()
现在,问题是结果行是((123,),(234,))或({'id':123},{'id':234}) 我要找的是(123,234)或[123,234]。如果我可以保存解析结果集,那就最好了。提前致谢
答案 0 :(得分:50)
那么列表理解呢?如果结果为((123,), (234,), (345,))
:
>>> row = [item[0] for item in cursor.fetchall()]
>>> row
[123, 234, 345]
如果结果为({'id': 123}, {'id': 234}, {'id': 345})
:
>>> row = [item['id'] for item in cursor.fetchall()]
>>> row
[123, 234, 345]
答案 1 :(得分:15)
我确信在这段时间之后,您已经解决了这个问题,但对于一些可能不知道如何使用MySQLdb将游标值作为字典获取的人,您可以使用此方法找到here:
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"]
答案 2 :(得分:10)
在搜索扁平化数据库查询时,这个旧版Q出现在Google上,所以这里有更多建议...
其他答案使用fetchall()
首先加载内存中的所有行,然后迭代它以创建一个新列表。可能效率低下。可以与MySQL结合使用所谓的server side cursor:
# 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()
但问题也标记为Django,它有一个很好的single field query flattener
class Bs(models.Model):
id_field = models.IntegerField()
list_of_ids = Bs.objects.values_list('id_field', flat=True)
答案 3 :(得分:1)
如果只有一个字段,我可以使用它来从数据库中创建一个列表:
def getFieldAsList():
kursor.execute("Select id from bs")
id_data = kursor.fetchall()
id_list = []
for index in range(len(id_data)):
id_list.append(id_data[index][0])
return id_list
答案 4 :(得分:1)
以这种方式制作光标对象:
db = MySQLdb.connect("IP", "user", "password", "dbname")
cursor = db.cursor(MySQLdb.cursors.DictCursor)
然后,当对查询执行cursor.fetchall()时,将获得一个字典元组,以后可以将其转换为列表。
data = cursor.fetchall()
data = list(data)
答案 5 :(得分:1)
list= [list[0] for list in cursor.fetchall()]
这会将结果呈现在一个列表中,例如-list = [122,45,55,44 ...]
答案 6 :(得分:-5)
cursor.execute("""Select * From bs WHERE (id = %s)""",(id))
cursor.fetchall()