add*_*ons 20 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:
        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
jjm*_*jjm 24
python标准的mysql库从cursor.execute返回元组.要获得你使用的question_id字段row[0],而不是row['question_id'].这些字段的出现顺序与它们在select语句中出现的顺序相同.
提取多个字段的一种不错的方法就像
for row in cursor.execute("select question_id, foo, bar from questions"):
    question_id, foo, bar = row
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"]
我知道这个问题已经过时了,但我找到了另一种方法,我认为它比公认的解决方案更好.所以我会把它放在这里,万一有人需要它.
创建光标时,您可以使用
cur = connection.cursor(dictionary=True);
这将允许您完全按照自己的意愿进行操作,无需任何其他修改.
rows = cur.fetchall()
for row in rows:
    print "%s %s %s" % (row["Id"], row["Name"], row["Price"])
| 归档时间: | 
 | 
| 查看次数: | 70265 次 | 
| 最近记录: |