繁体   English   中英

与python一起使用时,mysql为什么返回('abc')格式的字符串

[英]Why does mysql return string in format of ('abc') when used with python

编码:

cur = connection.cursor()
cur.execute("SELECT username from users where customer_id = %s", (cust))
name = cur.fetchone()

给出名称和客户的输出为: (u'abc',) (u'abc123',)

如何不使用(u' ')将其输出为适当的字符串?

您正在从数据库中获取一行 ,而不仅仅是一行 每行都是一个元组,并且由于查询返回的行中只包含一列,因此您会得到长度为1的元组。

如果您只想拥有一行的第一列,请使用索引:

name = cur.fetchone()[0]

元组中的列是一个unicode字符串,并且unicode字符串的python表示形式使用u前缀:

>>> u'unicode value'
u'unicode value'
>>> print u'unicode value'
unicode value

这使调试更加容易。 您可以直接将值复制回Python解释器,并知道您获得了完全相同的值。

在Python中打印标准容器(例如元组,字典,列表等)时,容器的内容始终使用表示形式:

>>> print ['list', 'with', 'strings']
['list', 'with', 'strings']
>>> print ['list', 'with', 'strings'][0]
list

(u“ foo”,)是具有一个元素的tuple u只是unicode字符串的前缀。 您可以通过索引获取字符串: name[0]

正如Martijn在回答中所说的那样,即使您只要求一列,您也将始终获取一个单列的行,而不是空列。 因此,将fetchone()的结果分配给诸如row类的变量比将其赋予诸如some_column_name类的变量可能更为清楚。 然后,您可以操纵该row以提取所需的特定数据。

您可能还会发现使用返回字典而不是元组的游标很有用。 像这样:

import MySQLdb.cursors

cur = connection.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute("SELECT username from users where customer_id = %s;", (cust,))
row = cur.fetchone()    # {'username': 'abc123'}
name = row['username']  # 'abc123'

对于将查询结果作为与列名称相对应的关键字参数发送到一些自定义函数或类中,这尤其好。 例如:

cur = connection.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute("SELECT name, age, years_in_residence FROM natural-born_citizens;")
query_result = cursor.fetchall()    # a tuple of dictionaries

def eligible(name, age, years_in_residence):
    if age >= 35 and years_in_residence >= 14:
        return '{} is eligible to run for U.S. President.'.format(name)
    else:
        return '{} is not eligible.'.format(name)

for row in query_result:
    print eligible(**row)

# Richard Stallman is eligible to run for U.S. President.
# Kermit the Frog is eligible to run for U.S. President.
# Miley Cyrus is not eligible.
# Oliver Smoot is eligible to run for U.S. President.

另请参阅: 使用***解压缩参数列表的文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM