Python - mysqlDB,sqlite 结果作为字典
当我做一些事情时,
sqlite.cursor.execute("SELECT * FROM foo")
result = sqlite.cursor.fetchone()
我认为必须记住列似乎能够取出它们的顺序,例如
result[0] is id
result[1] is first_name
有没有办法返回字典?所以我可以只使用 result['id'] 或类似的?
编号列的问题是,如果您编写代码然后插入一列,您可能必须更改代码,例如first_name的result[1]现在可能是date_joined,因此必须更新所有代码...
When I do someting like
sqlite.cursor.execute("SELECT * FROM foo")
result = sqlite.cursor.fetchone()
I think have to remember the order the columns appear to be able to fetch them out, eg
result[0] is id
result[1] is first_name
is there a way to return a dictionary? so I can instead just use result['id'] or similar?
The problem with the numbered columns is, if you write your code then insert a column you might have to change the code eg result[1] for first_name might now be a date_joined so would have to update all the code...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 mysqlDB 中执行此操作,只需将以下内容添加到 connect 函数调用中
Doing this in mysqlDB you just add the following to the connect function call
你可以很容易地做到这一点。对于 SQLite:
my_connection.row_factory = sqlite3.Row
查看 python 文档:http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index< /a>
更新:
You can do this very easily. For SQLite:
my_connection.row_factory = sqlite3.Row
Check it out on the python docs: http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index
UPDATE:
David Beazley 在他的 Python Essential Reference 中提供了一个很好的示例。
我手头没有这本书,但我认为他的例子是这样的:
示例用法:
David Beazley has a nice example of this in his Python Essential Reference.
I don't have the book at hand, but I think his example is something like this:
Sample usage:
sqlite3.Row 实例可以转换为 dict - 非常方便地将结果转储为 json
a sqlite3.Row instance can be converted to dict - very handy to dump a result as json