无法迭代元组列表 MySQLdb
Unable to iterate over tuple list MySQLdb
我有以下代码,我试图在其中迭代一个元组:
cust_list = ('138')
for cust in cust_list:
dbQuery = """
SELECT DISTINCT
c.id,
c.name,
c.email
FROM
customers c
WHERE
c.id = %s;
"""
cur1.execute(dbQuery, cust)
row = cur1.fetchone()
cust_name = row[1]
cust_email = row[2]
table个客户包含一条记录如下
id: 138
Name: Xoom Support
Email: support@example.com
对于元组中的单个值,我希望 for 循环到 运行 一次,但我得到以下错误:
Traceback (most recent call last):
File "/usr/local/bin/stats-test.py", line 80, in <module>
cust_name = row[1]
TypeError: 'NoneType' object has no attribute '__getitem__'
我试图打印产生以下内容的行:
(1L, 'Xoom Support', 'support@example.com')
^^^
|
What is this??
我对发生的事情一头雾水。
好的,您对 1L
的混淆让我发现了错误。迭代一个只有一个数字的元组和一个有两个数字的元组是有区别的,区别在于没有逗号。事实上,cust_list = ('138')
的类型是 String.
在第一种情况下,您将遍历数字的每个数字,而在第二种情况下,您将遍历每个数字。查看以下执行:
>>> cust_list = ('138')
>>> for cust in cust_list:
... print cust
...
1
3
8
>>> cust_list = ('138','123')
>>> for cust in cust_list:
... print cust
...
138
123
要编写包含单个值的元组,您必须包含一个逗号,即使只有一个值...
重新定义您的元组以获得所需的执行:
>>> cust_list = ('138',)
>>> for cust in cust_list:
... print cust
...
138
我有以下代码,我试图在其中迭代一个元组:
cust_list = ('138')
for cust in cust_list:
dbQuery = """
SELECT DISTINCT
c.id,
c.name,
c.email
FROM
customers c
WHERE
c.id = %s;
"""
cur1.execute(dbQuery, cust)
row = cur1.fetchone()
cust_name = row[1]
cust_email = row[2]
table个客户包含一条记录如下
id: 138
Name: Xoom Support
Email: support@example.com
对于元组中的单个值,我希望 for 循环到 运行 一次,但我得到以下错误:
Traceback (most recent call last):
File "/usr/local/bin/stats-test.py", line 80, in <module>
cust_name = row[1]
TypeError: 'NoneType' object has no attribute '__getitem__'
我试图打印产生以下内容的行:
(1L, 'Xoom Support', 'support@example.com')
^^^
|
What is this??
我对发生的事情一头雾水。
好的,您对 1L
的混淆让我发现了错误。迭代一个只有一个数字的元组和一个有两个数字的元组是有区别的,区别在于没有逗号。事实上,cust_list = ('138')
的类型是 String.
在第一种情况下,您将遍历数字的每个数字,而在第二种情况下,您将遍历每个数字。查看以下执行:
>>> cust_list = ('138')
>>> for cust in cust_list:
... print cust
...
1
3
8
>>> cust_list = ('138','123')
>>> for cust in cust_list:
... print cust
...
138
123
要编写包含单个值的元组,您必须包含一个逗号,即使只有一个值...
重新定义您的元组以获得所需的执行:
>>> cust_list = ('138',)
>>> for cust in cust_list:
... print cust
...
138