Python,将字典存储在数据库中 [英] Python, store a dict in a database

查看:55
本文介绍了Python,将字典存储在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据库中存储和检索python字典的最佳方法是什么?

What's the best way to store and retrieve a python dict in a database?

推荐答案

如果您对使用传统的SQL数据库(例如MySQL)不特别感兴趣,则可以研究非结构化文档数据库,其中文档自然映射到python词典,以实现以下目的:示例 MongoDB .MongoDB Python绑定允许您仅在数据库中插入字典,然后根据字典中的值查询它们.例如,请参见教程

If you are not specifically interested into using a traditionally SQL database, such as MySQL, you could look into unstructured document databases where documents naturally map to python dictionaries, for example MongoDB. The MongoDB python bindings allow you to just insert dicts in the DB, and query them based on the values in the dict. See for example the code below from the tutorial:

>>> from pymongo import Connection
>>> connection = Connection()
>>> db = connection['test-database']
>>> import datetime
>>> post = {"author": "Mike",
...         "text": "My first blog post!",
...         "tags": ["mongodb", "python", "pymongo"],
...         "date": datetime.datetime.utcnow()}
>>> posts = db.posts
>>> posts.insert(post)
ObjectId('...')
>>> posts.find_one({"author": "Mike"})
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}

这篇关于Python,将字典存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆