python连接mongodb操作数据示例(mongodb数据库配置类)

yipeiwu_com5年前Python基础

一、相关代码
数据库配置类 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()

相关文章

Python3中的最大整数和最大浮点数实例

Python中的最大整数 Python中可以通过sys模块来得到int的最大值. python2中使用的方法是 import sys max = sys.maxint print (...

Python 代码性能优化技巧分享

Python 代码性能优化技巧分享

如何进行 Python 性能优化,是本文探讨的主要问题。本文会涉及常见的代码优化方法,性能优化工具的使用以及如何诊断代码的性能瓶颈等内容,希望可以给 Python 开发人员一定的参考。...

PyQt Qt Designer工具的布局管理详解

PyQt Qt Designer工具的布局管理详解

前言 这节课很重要。。界面整洁美观与否就看布局了。。这里讲布局方法,至于设计的天赋与最终界面的美感那就看造化了。。 本文主要讲述Qt Designer工具实现界面控件布局管理,就是排列组...

Python绘制热力图示例

Python绘制热力图示例

本文实例讲述了Python绘制热力图操作。分享给大家供大家参考,具体如下: 示例一: # -*- coding: utf-8 -*- from pyheatmap.heatmap i...

Python装饰器入门学习教程(九步学习)

装饰器(decorator)是一种高级Python语法。装饰器可以对一个函数、方法或者类进行加工。在Python中,我们有多种方法对函数和类进行加工,比如在Python闭包中,我们见到函...