简体   繁体   English

为什么MySQL Connecter查询的输出作为嵌套列表项返回?

[英]Why does the Output for a MySQL Connecter Query return as a nested list item?

Why does this print into a list and not just as a string? 为什么将此打印到列表中而不是仅打印为字符串?

import mysql.connector
from mysql.connector import errorcode


config = {
  'user': 'user',
  'password': 'xxxxx',
  'host': '127.0.0.1',
  'database': 'ThatDBTho',
  'raise_on_warnings': True,
}

try:
    cnx = mysql.connector.connect(**config)

    cur = cnx.cursor(buffered=True)

    cur.execute("SELECT `street` FROM `Service` WHERE `address` = '123456'")
    example = (cur.fetchall())
    cur.close()
    cnx.close()

except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exists")
    else:
        print(err)
else:
    cnx.close()

print example

The follwing prints out like this: 如下所示打印:

[root@localhost Test Python Scripts]# python heewee.py
[(u'Maple',)]

By adding this print statement I am able to get the string out, BUT this is just more overhead: 通过添加此打印语句,我可以取出字符串,但是这只会增加开销:

for x in example:
    for x in x:
        print x

Giving me the output with the original code with the new for loop to print the list item to string: 给我输出带有原始代码的新for循环,以将列表项打印为字符串:

[root@localhost Test Python Scripts]# python heewee.py
Maple
[(u'Maple',)]

Because that's what the API requires for fetchall() : 因为这就是API对fetchall()要求:

fetchall()

Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (eg a list of tuples). 提取查询结果的所有(剩余)行,并将它们作为序列序列(例如,元组列表)返回。 Note that the cursor's arraysize attribute can affect the performance of this operation. 请注意,游标的arraysize属性会影响此操作的性能。

So because *all will usually return multiple rows, the result is always a list of rows. 因此,由于*all通常会返回多行,因此结果始终是行列表。 And because a row often contains several columns, the row itself is a sequence (a tuple). 而且由于一行通常包含几列,所以该行本身就是一个序列(元组)。

(It would be a horroble API if most of the time, it returned a list of rows (resp. columns), but sometimes only a single row (resp. column), only because your query happened to only match a single row or select a single column. That would be completely unpredictable.) (如果在大多数情况下,它返回行(resp。列)的列表,但有时只返回一行(resp。列),那将是一个糟糕的API,这仅仅是因为您的查询碰巧仅匹配一行或select一列。这完全是不可预测的。)

Use fetchone() if you only want to retrieve exactly one row: 如果只想精确检索一行,请使用fetchone()

>>> row = cur.fetchone()
>>> row
(u'Maple',)
>>>
>>> row[0]
u'Maple'

Why does this print into a list ? 为什么将此打印到列表中?

Because when a query is excecuted, there may be a number of rows which is selected and all these rows must be returned. 因为执行查询时,可能会选择许多行,因此必须返回所有这些行。 The different rows selected are so returned as a list. 所选的不同行将作为列表返回。

Within each list, each row is represented as a tuple of values, corresponding to the column values selected. 在每个列表中,每一行都表示为值的元组,对应于所选的列值。

暂无
暂无

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

相关问题 为什么mysql.connecter python准备语句在bytearray中返回字符串 - Why mysql.connecter python prepared statement returns string in bytearray 返回嵌套列表中的项目(python) - Return an item in a nested list (python) 为什么Python的set()返回一个设置项而不是一个列表 - Why does Pythons' set() return a set item instead of a list 为什么退货是清单的项目,而不是清单itef - Why the return is a item of the list, not the list itsef 为什么从单个列表构造的双端队列返回其项目而不是列表本身? - Why does a deque constructed from a single list return its item rather than the list itself? 当列表推导式返回所有内容时,为什么 for 循环只返回第一项? - Why does a for loop return only the first item when a list comprehension returns everything? 为什么存储函数调用pop不会在修改列表实例时返回最后一项? - Why does storing a function call to pop not return the last item when the list instance is modified? 如果只有 int 1 是 [1, 2.3, 'blabla'] 中的列表项,为什么 Python ''in operator'' 为 float 1.0 返回 'True'? - Why does Python ''in operator'' return 'True' for float 1.0 if only the int 1 is a list item in [1, 2.3, 'blabla']? 为什么此列表插入嵌套列表? - Why does this List insert a nested List? 为什么 db.query(Item).all().filter(Item.is_active == True) 失败并出现错误 AttributeError: 'list' object has no attribute 'filter' - why does db.query(Item).all().filter(Item.is_active == True) fail with error AttributeError: 'list' object has no attribute 'filter'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM