psycopg2 - TypeError: 'int' object is not subscriptable

psycopg2 - TypeError: 'int' object is not subscriptable

我正在使用存储在函数 columnsearch() 中的 psycopg2 执行 postgres 查询。我的目标是能够通过使用return 语句中的列名来查看每个字段中的数据。我收到错误消息:

TypeError: 'int' object is not subscriptable

有谁知道我该如何纠正这个问题?

def columnsearch():
     con = psycopg2.connect(connectstring)
     cur = con.cursor(cursor_factory=e.DictCursor)
     cur.execute("SELECT * FROM radio_archive_ind.radio_archive_ind WHERE tape_number = 'TP00001'")
     rows = cur.fetchone()
     for r in rows:
             return r["tape_number"]

print columnsearch()

注意 .fetchone() returns a single sequence 所以你可以这样做:

def columnsearch():
     con = psycopg2.connect(connectstring)
     cur = con.cursor(cursor_factory=e.DictCursor)
     cur.execute("""SELECT * 
                      FROM radio_archive_ind.radio_archive_ind 
                     WHERE tape_number = 'TP00001'""")
     row = cur.fetchone()
     return row["tape_number"]