将字典存储在数据库中
我创建一个Berkeley数据库,并使用bsddb模块对其进行操作.我需要以一种样式存储信息,例如:
I create a Berkeley database, and operate with it using bsddb module. And I need to store there information in a style, like this:
username = '....'
notes = {'name_of_note1':{
'password':'...',
'comments':'...',
'title':'...'
}
'name_of_note2':{
#keys same as previous, but another values
}
}
这就是我打开数据库的方式
This is how I open database
db = bsddb.btopen['data.db','c']
我该怎么做?
因此,首先,我想您应该使用括号打开数据库:
So, first, I guess you should open your database using parentheses:
db = bsddb.btopen('data.db','c')
请记住,伯克利的模式是key-> value,其中key和value都是字符串对象(不是unicode).在您的情况下,最好的方法是使用:
Keep in mind that Berkeley's pattern is key -> value, where both key and value are string objects (not unicode). The best way in your case would be to use:
db[str(username)] = json.dumps(notes)
因为您的注释与json语法兼容.
since your notes are compatible with the json syntax.
但是,如果您只想查询用户名的注释,这不是一个很好的选择.您应该使用关系数据库,例如sqlite,它也是Python内置的.
However, this is not a very good choice, say, if you want to query only usernames' comments. You should use a relational database, such as sqlite, which is also built-in in Python.