是否有一种方法可以使用列名而不是Python中的列索引来检索SQL结果列值?
result = `select name, deptname from employee;`我试过一次:
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT name, category FROM animal")
result_set = cursor.fetchall()
for row in result_set:
print "%s, %s" % (row["name"], row["deptname"])这里我有个错误,比如:
TypeError: tuple indices must be integers, not str有什么帮助会很棒吗?
发布于 2016-05-01 14:14:04
您没有正确地指定需要字典游标。当您调用connect()方法时,设置cursorclass
import MySQLdb
conn = MySQLdb.connect(user='user',
passwd='password',
db='db_name',
cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()发布于 2016-05-01 14:17:21
实际上你得到了你想要的。您只需要使用行不是作为字典,而是作为元组。这意味着索引是数字,而不是字符串。试一试
print "%s, %s" % (row[0], row[1])相反,
https://stackoverflow.com/questions/36967565
复制相似问题