如何使用MySql数据库在Python中使用列名检索SQL结果列值?

2024-04-20 08:13:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,有没有一种方法可以使用列名而不是列索引来检索SQL结果列值?在

result = `select name, deptname from employee;`

我试过以下一种:

^{pr2}$

这里有个错误,比如:

TypeError: tuple indices must be integers, not str

有什么帮助会很棒吗?在


Tags: 方法namefromsql错误employeeresultselect
2条回答

您没有正确指定需要字典光标。当您调用connect()方法时,请设置cursorclass

import MySQLdb

conn = MySQLdb.connect(user='user', 
                       passwd='password', 
                       db='db_name', 
                       cursorclass=MySQLdb.cursors.DictCursor) 
cursor = conn.cursor()

实际上你得到了你想要的。 您只需要将行用作元组而不是字典。 这意味着索引是数字,而不是字符串。 试试看

print "%s, %s" % (row[0], row[1])

取而代之的是

相关问题 更多 >