cursor.fetchall() 使用 MySQldb 和 python 返回额外的字符 [英] cursor.fetchall() returns extra characters using MySQldb and python

查看:46
本文介绍了cursor.fetchall() 使用 MySQldb 和 python 返回额外的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 python 从 SQL 数据库中获取结果时,我会在返回值的开头和结尾处获得额外的宪章.例如,下面的代码返回 ((56L,),) 而不是 56,有谁知道如何获取值...以及 ((,),) 的实际含义...?

When I'm using python to fetch results from a SQL database I get extra charters at the beginning and end of the returned value. For example the below code returns ((56L,),) instead of 56, does anyone know how to get just the value... and what the (( ,),) actually mean...?

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  

推荐答案

fetchall() 返回一个元组列表(实际上:元组).将其视为一系列行,其中每一行都是列中的一系列项目.如果您确定您的搜索将只返回 1 行,请使用 fetchone(),它返回一个元组,它更易于解包.以下是从 fetchall() 和 fetchone() 中提取所需内容的示例:

fetchall() returns a list (really: a tuple) of tuples. Think of it as a sequence of rows, where each row is a sequence of items in the columns. If you are sure your search will return only 1 row, use fetchone(), which returns a tuple, which is simpler to unpack. Below are examples of extracting what you want from fetchall() and fetchone():

# Use fetchall():
((points,),) = cursor.fetchall()  # points = 56L

# Or, if you use fetchone():
(points,) = cursor.fetchone()     # points = 56L

这篇关于cursor.fetchall() 使用 MySQldb 和 python 返回额外的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆