Python, store a dict in a database

前端 未结 4 1122
青春惊慌失措
青春惊慌失措 2021-02-05 16:14

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

4条回答
  •  悲哀的现实
    2021-02-05 16:38

    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']}
    

提交回复
热议问题