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

yipeiwu_com6年前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()

相关文章

更改Python命令行交互提示符的方法

一、定制Python的交互提示符 Python的默认交互提示符为“>>>”,但它是可以定制的。 Python启动后,先寻找PYTHONSTARTUP环境变量,然后执行此...

Python实现socket非阻塞通讯功能示例

本文实例讲述了Python实现socket非阻塞通讯功能。分享给大家供大家参考,具体如下: 非阻塞需要多线程编程 服务端 方式1: 使用threading库实现多线程 基本方法和单进程基...

Django入门使用示例

Django入门使用示例

Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。 Django是一个开放源代码的Web应用框架,由Pyt...

Python虚拟环境的原理及使用详解

Python的虚拟环境极大地方便了人们的生活。本指南先介绍虚拟环境的基础知识以及使用方法,然后再深入介绍虚拟环境背后的工作原理。 注意:本指南在macOS Mojave系统上使用最新版本...

在Mac OS上搭建Python的开发环境

一. 安装python mac系统其实自带了一个python的执行执行环境,用来运行python还行,但是开发可能就不够了,因此我们需要重新安装python。这里有两种方案安装: 1.h...