First, the relevant code
Database Configuration Class mongodbconn.py
The code is as follows:
#encoding =utf-8
'''
Mongo Conn Connection Class
'''
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 class
The code is as follows:
#encoding =utf-8
'''
MONGO Operation 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": "Test 1", "Age": 25},
{"Name": "Steven2", "realname": "Test 2", "Age": 26},
{"Name": "Steven1", "realname": "Test 3", "Age": 23}]
Lifeba_users.insert (Datas)
Def updatedata ():
"' only modify the last matching data
The 3rd parameter is set to TRUE and the data is not found to add a
The 4th parameter is set to True, and multiple records are not updated
'''
Lifeba_users.update ({' name ': ' Steven1 '},{' $set ': {' realname ': ' Test 1 Modified '}}, 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 ():
"Create libraries and Tables"
Global Lifeba_users
Lifeba_users = Conn.lifeba.users
Def droptable ():
"Delete Table"
Global Conn
Conn.drop_database ("Lifeba")
def printresult (rows):
For row in rows:
For key in Row.keys (): #遍历字典
Print Row[key], #加, no line break printing
print '
if __name__ = = ' __main__ ':
Process ()