Python从fetchone()中检索单个项目

时间:2015-07-28 18:55:15

标签: python

我在python中有一个SQL查询,如果它存在,则检索第一,第四和第五列元素

cur2.execute('SELECT * FROM duplicates where TITLE=?', [post_title])   
sql2.commit()
if cur2.fetchone():
    repost_permalink = cur.fetchone()[0]
    repost_title = cur.fetchone()[3]
    repost_submitter = cur.fetchone()[4]

因为某些原因我不断收到错误:

repost_permalink = cur.fetchone()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

我是否错误地访问了该元素?

1 个答案:

答案 0 :(得分:2)

每次拨打fetchone()时,都会抓取另一行。因此,您在代码中提取了四个不同的行,因为您调用了fetchone四次。如果结果集中没有那么多行,则其中一些行将为None。

如果要获取单行的一部分,请存储该行,然后访问它:

row = cur2.fetchone()
if row:
    repost_permalink = row[0]
    repost_title = row[3]
    repost_submitter = row[4]