Python:从mysql表中选择时,元组索引必须是整数,而不是str

Python:从mysql表中选择时,元组索引必须是整数,而不是str,python,mysql,tuples,Python,Mysql,Tuples,我有下面的方法,从表中选择所有ID并将它们附加到列表中,然后返回该列表。但当执行这段代码时,我得到的元组标记必须是整数。。。错误。我已附上错误和打印件以及我的方法: def questionIds(con): print 'getting all the question ids' cur = con.cursor() qIds = [] getQuestionId = "SELECT question_id from questions_new" try

我有下面的方法,从表中选择所有ID并将它们附加到列表中,然后返回该列表。但当执行这段代码时,我得到的元组标记必须是整数。。。错误。我已附上错误和打印件以及我的方法:

def questionIds(con):
    print 'getting all the question ids'
    cur = con.cursor()
    qIds = []
    getQuestionId = "SELECT question_id from questions_new"
    try:
        cur.execute(getQuestionId)
        for row in cur.fetchall():
            print 'printing row'
            print row
            qIds.append(str(row['question_id']))
    except Exception, e:
        traceback.print_exc()
    return qIds
打印我的方法的作用:

Database version : 5.5.10 
getting all the question ids
printing row
(u'20090225230048AAnhStI',)
Traceback (most recent call last):
  File "YahooAnswerScraper.py", line 76, in questionIds
    qIds.append(str(row['question_id'][0]))
TypeError: tuple indices must be integers, not str

是一个元组。当您执行
行['question\u id']
时,您试图使用字符串索引访问元组,这会给您一个错误。

python标准mysql库从cursor.execute返回元组。要获取问题id字段,您可以使用
行[0]
,而不是
行['question\u id']
。字段的显示顺序与select语句中的显示顺序相同

提取多个字段的合适方法如下

for row in cursor.execute("select question_id, foo, bar from questions"):
    question_id, foo, bar = row
你可以在这里看到:,我想这是你想要的

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite


con = lite.connect('test.db')    

with con:

    con.row_factory = lite.Row # its key

    cur = con.cursor() 
    cur.execute("SELECT * FROM Cars")

    rows = cur.fetchall()

    for row in rows:
        print "%s %s %s" % (row["Id"], row["Name"], row["Price"])

MySQLdb模块中有多种游标类型。默认游标返回元组中的数据。当我们使用字典游标时,数据以Python字典的形式发送。这样我们就可以通过数据的列名来引用数据


不允许使用整数索引。要使其工作,您可以按照以下指定声明DICT:

VarName = {}

希望这对您有用。

要从数据库检索数据,请使用字典游标

import psycopg2
import psycopg2.extras
con = psycopg2.connect(database="test", user="test", password="test", host="localhost", port="5432")
if con != None:
    print "Connection Established..!\n"
else:
    print "Database Connection Failed..!\n"

cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)

cur.execute("SELECT * FROM emp")
rows = cur.fetchall()
for row in rows:
    print "%s %s %s" % (row["id"],row["name"],row["address"])

print "\nRecords Display Successfully"
con.commit()
con.close()

我知道这个问题由来已久,但我找到了另一种方法,我认为它比公认的解决方案更好。所以我就把它留在这里,以防有人需要

创建光标时,可以使用

cur = connection.cursor(dictionary=True);
这将允许您在不进行任何额外修改的情况下完全执行您想要的操作

rows = cur.fetchall()
for row in rows:
    print "%s %s %s" % (row["Id"], row["Name"], row["Price"])

因此,我尝试了以下行['question_id'][0],但它仍然给出了相同的答案
是一个元组。元组如下所示:
t=('a','b','c')
。您可以使用整数索引访问它们,即
t[0]='a'
t[1]='b'
t[2]='c'
。不能使用字符串作为索引来访问它们;您只能使用
dict
来执行此操作。如果希望能够按列名提取列值,您可能需要尝试使用MySQLdb.cursors.DictCursor创建光标。看见
rows = cur.fetchall()
for row in rows:
    print "%s %s %s" % (row["Id"], row["Name"], row["Price"])