[英]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.