python连接mongodb操作数据示例(mongodb数据库配置类)
程序员文章站
2022-05-30 20:36:11
一、相关代码数据库配置类 mongodbconn.py
复制代码 代码如下:#encoding=utf-8'''mongo conn连接类'''import pymong...
一、相关代码
数据库配置类 mongodbconn.py
复制代码 代码如下:
#encoding=utf-8
'''
mongo conn连接类
'''
import pymongo
class dbconn:
conn = none
servers = "mongodb://localhost:27017"
def connect(self):
self.conn = pymongo.connection(self.servers)
def close(self):
return self.conn.disconnect()
def getconn(self):
return self.conn
mongodemo.py 类
复制代码 代码如下:
#encoding=utf-8
'''
mongo操作demo
done:
'''
import mongodbconn
dbconn = mongodbconn.dbconn()
conn = none
lifeba_users = none
def process():
#建立连接
dbconn.connect()
global conn
conn = dbconn.getconn()
#列出server_info信息
print conn.server_info()
#列出全部数据库
databases = conn.database_names()
print databases
#删除库和表
droptable()
#添加数据库lifeba及表(collections)users
createtable()
#插入数据
insertdatas()
#更新数据
updatedata()
#查询数据
querydata()
#删除数据
deletedata()
#释放连接
dbconn.close()
def insertdatas():
datas=[{"name":"steven1","realname":"测试1","age":25},
{"name":"steven2","realname":"测试2","age":26},
{"name":"steven1","realname":"测试3","age":23}]
lifeba_users.insert(datas)
def updatedata():
'''只修改最后一条匹配到的数据
第3个参数设置为true,没找到该数据就添加一条
第4个参数设置为true,有多条记录就不更新
'''
lifeba_users.update({'name':'steven1'},{'$set':{'realname':'测试1修改'}}, false,false)
def deletedata():
lifeba_users.remove({'name':'steven1'})
def querydata():
#查询全部数据
rows = lifeba_users.find()
printresult(rows)
#查询一个数据
print lifeba_users.find_one()
#带条件查询
printresult(lifeba_users.find({'name':'steven2'}))
printresult(lifeba_users.find({'name':{'$gt':25}}))
def createtable():
'''创建库和表'''
global lifeba_users
lifeba_users = conn.lifeba.users
def droptable():
'''删除表'''
global conn
conn.drop_database("lifeba")
def printresult(rows):
for row in rows:
for key in row.keys():#遍历字典
print row[key], #加, 不换行打印
print ''
if __name__ == '__main__':
process()