标签:pre 判断 获取 xxx got 存在 add list 插入
之前捣鼓了下mysql。后来想想。python似乎更加适合配合nosql来使用。然后自己又搭建了下mongodb来耍一下
试过之后果然是比mysql爽多了。不用说,封装封装。
import pymongo class MongoHp: def __init__(self,addr,port,dbName,tableName=None): self.conn=pymongo.MongoClient(addr,port) self.db=self.conn[dbName] self.tableName=tableName self.dbName=dbName self.addr=addr self.port=port if tableName: self.tb = self.db[tableName] #插入一条数据 def insert(self,data,tableName=None): mytb=self.getTable(tableName) if mytb: mytb.insert_one(data) return True return False #批量插入数据 def insertAll(self,list,tableName=None): mytb = self.getTable(tableName) if mytb: mytb.insert(list) return True return False #符合条件才插入数据,例如要插入一个值时,判断该表中不存在当前数据。才进行插入 def insertSig(self,reason,data,tableName): mytb = self.getTable(tableName) if mytb: mytb.update_one(reason,data) return True #获取指定的数据 def find(self,data,tableName=None): mytb = self.getTable(tableName) if mytb: return mytb.find(data) return False #如果需要特殊的操作可以将表获取出去操作 def getTable(self,tableName=None): if tableName: return self.db[tableName] if self.tableName: return self.tb return False def remove(self,reason=None,tableName=None): mytb = self.getTable(tableName) if mytb: if reason: mytb.remove(reason) else: mytb.remove() return True return False #获取指定表数据数量 def count(self,tableName=None,reason=None): mytb=self.getTable(tableName) if mytb: if reason: mytb.count(reason) else: return mytb.count() #修改默认管理的表 def setTable(self,tableName=None): self.tableName=tableName
然后随便测试了下。果然很方便。居家必备啊
import mongotest db=mongotest.MongoHp("xxxx.xxxx.xxxx.xxxx",27017,"mongodata","mytable1") t1={"name":"wang"} t2={"name":"jiang"} t3={"name":"li"} db.insert(t1) db.insert(t2) db.insert(t3) datas= db.find({"name":"wang"}) for item in datas: print(item) cnt=db.count() print(cnt) db.remove(t1) cnt=db.count() print(cnt) db.insert(t1,"mytable2") cnt=db.count("mytable2") print(cnt)
标签:pre 判断 获取 xxx got 存在 add list 插入
原文地址:http://www.cnblogs.com/kings0/p/7810178.html