I have following method that I select all the ids from table and append them to a list and return that list. But when execute this code I end up getting tuple indicies must be integers... error. I have attached the error and the print out along with my method:
我有以下方法,我从表中选择所有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
Printing what my method does:
打印我的方法:
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
7 个解决方案
#1
23
The python standard mysql library returns tuples from cursor.execute. To get at the question_id field you'd use row[0]
, not row['question_id']
. The fields come out in the same order that they appear in the select statement.
python标准的mysql库从cursor.execute返回元组。要获取question_id字段,您需要使用row [0],而不是row ['question_id']。这些字段的出现顺序与它们在select语句中出现的顺序相同。
A decent way to extract multiple fields is something like
提取多个字段的一种不错的方法就像
for row in cursor.execute("select question_id, foo, bar from questions"):
question_id, foo, bar = row
#2
7
There are multiple cursor types in the MySQLdb module. The default cursor returns the data in a tuple of tuples. When we use a dictionary cursor, the data is sent in a form of Python dictionaries. This way we can refer to the data by their column names. Source
MySQLdb模块中有多种游标类型。默认游标返回元组元组中的数据。当我们使用字典光标时,数据以Python字典的形式发送。这样我们就可以通过列名来引用数据。资源
#!/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"]
#3
4
I know the question is old, but I found another way to do it that I think it is better than the accepted solution. So I'll just leave it here in case anyone needs it.
我知道问题已经过时了,但我发现了另一种方法,我认为这比接受的解决方案更好。所以我会把它放在这里,万一有人需要它。
When creating the cursor you can use
创建光标时,您可以使用
cur = connection.cursor(dictionary=True);
which will allow you to do exactly what you want without any additional modifications.
这将允许您完全按照自己的意愿进行操作,无需任何其他修改。
rows = cur.fetchall()
for row in rows:
print "%s %s %s" % (row["Id"], row["Name"], row["Price"])
#4
1
you can see here: enter link description here ,I think its your want
你可以在这里看到:在这里输入链接描述,我想你想要的
#!/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"])
#5
1
To retrieve data from database use dictionary cursor
从数据库中检索数据使用字典光标
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()
#6
0
Integer indices are not allowed. To get it working you can declare the DICT as specified below:
不允许使用整数索引。为了使其正常工作,您可以按照以下规定声明DICT:
VarName = {}
Hope this works for you.
希望这对你有用。
#7
-1
row
is a tuple. When you do row['question_id']
, you are trying to access a tuple using a string index which gives you an error.
行是一个元组。当您执行row ['question_id']时,您尝试使用字符串索引访问元组,这会给您一个错误。
#1
23
The python standard mysql library returns tuples from cursor.execute. To get at the question_id field you'd use row[0]
, not row['question_id']
. The fields come out in the same order that they appear in the select statement.
python标准的mysql库从cursor.execute返回元组。要获取question_id字段,您需要使用row [0],而不是row ['question_id']。这些字段的出现顺序与它们在select语句中出现的顺序相同。
A decent way to extract multiple fields is something like
提取多个字段的一种不错的方法就像
for row in cursor.execute("select question_id, foo, bar from questions"):
question_id, foo, bar = row
#2
7
There are multiple cursor types in the MySQLdb module. The default cursor returns the data in a tuple of tuples. When we use a dictionary cursor, the data is sent in a form of Python dictionaries. This way we can refer to the data by their column names. Source
MySQLdb模块中有多种游标类型。默认游标返回元组元组中的数据。当我们使用字典光标时,数据以Python字典的形式发送。这样我们就可以通过列名来引用数据。资源
#!/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"]
#3
4
I know the question is old, but I found another way to do it that I think it is better than the accepted solution. So I'll just leave it here in case anyone needs it.
我知道问题已经过时了,但我发现了另一种方法,我认为这比接受的解决方案更好。所以我会把它放在这里,万一有人需要它。
When creating the cursor you can use
创建光标时,您可以使用
cur = connection.cursor(dictionary=True);
which will allow you to do exactly what you want without any additional modifications.
这将允许您完全按照自己的意愿进行操作,无需任何其他修改。
rows = cur.fetchall()
for row in rows:
print "%s %s %s" % (row["Id"], row["Name"], row["Price"])
#4
1
you can see here: enter link description here ,I think its your want
你可以在这里看到:在这里输入链接描述,我想你想要的
#!/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"])
#5
1
To retrieve data from database use dictionary cursor
从数据库中检索数据使用字典光标
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()
#6
0
Integer indices are not allowed. To get it working you can declare the DICT as specified below:
不允许使用整数索引。为了使其正常工作,您可以按照以下规定声明DICT:
VarName = {}
Hope this works for you.
希望这对你有用。
#7
-1
row
is a tuple. When you do row['question_id']
, you are trying to access a tuple using a string index which gives you an error.
行是一个元组。当您执行row ['question_id']时,您尝试使用字符串索引访问元组,这会给您一个错误。