无法迭代元组列表MySQLdb

时间:2016-02-09 14:28:52

标签: python mysql-python

我有以下代码,我试图迭代一个元组:

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]

表客户包含如下记录

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??

我对发生的事情感到非常困惑。

1 个答案:

答案 0 :(得分:2)

好的,你对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