Chinaunix首页 | 论坛 | 博客
  • 博客访问: 818262
  • 博文数量: 97
  • 博客积分: 3042
  • 博客等级: 中校
  • 技术积分: 1610
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-21 11:48
文章存档

2015年(1)

2014年(3)

2013年(4)

2012年(43)

2011年(44)

2010年(2)

分类: LINUX

2014-02-21 20:32:58

一、相关代码

数据库配置类MongoDBConn.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#encoding=utf-8
'''
Created on 2012-11-12
 
@author: Steven
 
 
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类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#encoding=utf-8
'''
Created on 2012-11-12
 
@author: Steven
 
 
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()

二、打包下载

阅读(1381) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~