Python: tuple indices must be integers, not str when selecting from mysql table
我有以下方法,我从表中选择所有ID,然后将它们附加到列表中并返回该列表。 但是,当执行此代码时,我最终得到的元组索引必须是整数...错误。 我已附上错误和打印结果以及我的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
打印我的方法做什么:
1 2 3 4 5 6 7 8 | 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 |
python标准mysql库从cursor.execute返回元组。要使用question_id字段,请使用
提取多个字段的一种不错的方法是
1 2 | for row in cursor.execute("select question_id, foo, bar from questions"): question_id, foo, bar = row |
MySQLdb模块中有多种游标类型。默认游标以元组的元组返回数据。当我们使用字典游标时,数据以Python字典的形式发送。这样,我们可以通过列名称来引用数据。资源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mdb con = mdb.connect('localhost', 'testuser', 'test623', 'testdb') with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM Writers LIMIT 4") rows = cur.fetchall() for row in rows: print row["Id"], row["Name"] |
我知道这个问题很老,但是我发现另一种解决方法,认为它比公认的解决方案更好。因此,只要有人需要,我就把它留在这里。
创建游标时,您可以使用
1 | cur = connection.cursor(dictionary=True); |
这将使您无需做任何其他修改即可完全按照自己的意愿做。
1 2 3 | rows = cur.fetchall() for row in rows: print"%s %s %s" % (row["Id"], row["Name"], row["Price"]) |
要从数据库检索数据,请使用字典光标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import psycopg2 import psycopg2.extras con = psycopg2.connect(database="test", user="test", password="test", host="localhost", port="5432") if con != None: print"Connection Established..!\ " else: print"Database Connection Failed..!\ " 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"\ Records Display Successfully" con.commit() con.close() |
你可以在这里看到:在这里输入链接描述,我认为这是你想要的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #!/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"]) |
不允许使用整数索引。要使其正常工作,您可以按以下说明声明DICT:
1 | VarName = {} |
希望这对您有用。