当前位置:首页 » python教程 » 正文

Python LMDB库的使用示例

看: 736次  时间:2021-04-05  分类 : python教程

linux中,可以使用指令

pip install lmdb

安装lmdb包。

----

  1. lmdb 数据库文件生成
  2. 增 改 删

1、生成一个空的lmdb数据库文件

# -*- coding: utf-8 -*-
import lmdb
# 如果train文件夹下没有data.mbd或lock.mdb文件,则会生成一个空的,如果有,不会覆盖
# map_size定义最大储存容量,单位是kb,以下定义1TB容量
env = lmdb.open("./train",map_size=1099511627776)
env.close()

2、LMDB数据的添加、修改、删除

# -*- coding: utf-8 -*-
import lmdb
# map_size定义最大储存容量,单位是kb,以下定义1TB容量
env = lmdb.open("./train", map_size=1099511627776)
txn = env.begin(write=True)

# 添加数据和键值
txn.put(key = '1', value = 'aaa')
txn.put(key = '2', value = 'bbb')
txn.put(key = '3', value = 'ccc')

# 通过键值删除数据
txn.delete(key = '1')

# 修改数据
txn.put(key = '3', value = 'ddd')

# 通过commit()函数提交更改
txn.commit()
env.close()

3、查询LMDB数据库

# -*- coding: utf-8 -*-
import lmdb

env = lmdb.open("./train")

# 参数write设置为True才可以写入
txn = env.begin(write=True)
############################################添加、修改、删除数据

# 添加数据和键值
txn.put(key = '1', value = 'aaa')
txn.put(key = '2', value = 'bbb')
txn.put(key = '3', value = 'ccc')

# 通过键值删除数据
txn.delete(key = '1')

# 修改数据
txn.put(key = '3', value = 'ddd')

# 通过commit()函数提交更改
txn.commit()
############################################查询lmdb数据
txn = env.begin()

# get函数通过键值查询数据
print txn.get(str(2))

# 通过cursor()遍历所有数据和键值
for key, value in txn.cursor():
  print (key, value)

############################################
env.close()

4. 读取已有.mdb文件内容

# -*- coding: utf-8 -*-
import lmdb

env_db = lmdb.Environment('trainC')
# env_db = lmdb.open("./trainC")

txn = env_db.begin()

# get函数通过键值查询数据,如果要查询的键值没有对应数据,则输出None
print txn.get(str(200))

for key, value in txn.cursor(): #遍历
  print (key, value)

env_db.close()

以上就是Python LMDB库的使用示例的详细内容,更多关于Python LMDB库的资料请关注python博客其它相关文章!

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!