cursor.fetchall() 使用 MySQLdb 和 Python 返回多余字符
我在用Python从SQL数据库获取结果时,发现返回的值前后多了些字符。比如下面的代码返回的是((56L,),)而不是56。有没有人知道怎么只获取这个值呢?还有这个(( ,),)到底是什么意思呢?
hp= 56
id= 3
database = MySQLdb.connect (host="localhost", user = "root", passwd = "", db = "db")
cursor = database.cursor()
cursor.execute("UPDATE period_option SET points =%s WHERE period_option_id =%s", (hp, id))
cursor.execute("SELECT points FROM period_option WHERE period_option_id =%s", (po_id_home))
results = cursor.fetchall()
print results
4 个回答
3
如果你只是想从查询中获取一个值,可以直接取第一个值,也就是索引为0的那个。
results = cursor.fetchall()
如果结果只有一个值,就用results[0]
。这样可以得到你想要的那个值。
有时候,当我们运行查询时,结果会非常庞大,这种情况下,我们需要逐个查看这些值,并把它们放到一个列表里。
>>> result
('58',)
>>> result[0]
'58'
当你查询大量数据时,使用curosr.fetchall()后,你会得到类似这样的输出:
(('58',),('50',),('10'),)
使用下面的代码可以把数据以列表的形式获取:
>>> results=(('58',),('50',),('10'),)
>>>[x[0] for x in results] --> code
['58', '50', '1']
3
试试下面这个方法,它可以帮助你把fetchall()的输出转换成更好用的列表:
row = cursor.fetchall()
print row
output is : [(1,), (2,), (3,), (4,)]
num = list(sum(row, ()))
print num
output is : [1, 2, 3, 4]
9
fetchall()
会返回一个列表(实际上是一个元组的列表),可以把它想象成一系列的行,每一行又是一系列的列项。如果你确定你的查询只会返回一行数据,可以使用 fetchone()
,它会返回一个元组,这样提取数据会更简单。下面是从 fetchall()
和 fetchone()
中提取你想要的数据的例子:
# Use fetchall():
((points,),) = cursor.fetchall() # points = 56L
# Or, if you use fetchone():
(points,) = cursor.fetchone() # points = 56L