一、相關代碼
資料庫配置類 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()