代码:
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.
另请参阅:使用*
和**
解压缩参数列表的文档