最近学习了MangoDB 和 面向对象的MangoEngine 感觉很好用,况且利用python来调用将数据写入也很简单,代码如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from mongoengine import *
import pymongo
import sys
import time
connect('ceshi')
class People(Document): #这个类集成 mongoengine 的Document的类
    ID   = StringField(required=True)
    name = StringField(required=True)
    age  = StringField(required=True)
    salary = StringField(required=True)

class Database(object):
    def __init__(self):
        self.HELP = '''
                    创建:insert id=1,name=a,age=18,saraly=5000
                    查询所有:show all
                    查询指定:select id=123 
                    修改:update id=1,name=hi
                    删除:delete id=1
                    帮助:help,man
                    退出:exit,quit
                    '''
        print('''                          
        Welcome To Small Database information management system''')
        print('''
                ____________
                ||||||||||||=========================================
                ||||||||||||=========================================
                ||||||||||||                


        ******************************
            Successful Connection!!    
        ****************************''' )         
        self.key = {}
        self.run()
    def run(self):
        while True:
            try:
                cmd = str(raw_input('Mongodb: '))
                cmd = cmd.strip()
                if cmd == '':
                    pass
                elif (cmd == 'exit') or (cmd == 'quit'):
                    print('Bey')
                    sys.exit(1) 
                elif (cmd == 'help') or (cmd == 'man'):
                    print(self.HELP)
                elif (cmd.startswith('insert')) and (len(cmd.split(',')) == 4):
                    cmd = cmd.replace('insert','').lstrip()
                    if  People.objects(ID=cmd.split(',',1)[0][3:]).count() == 0:
                        self.key['id'] = cmd.split(',',1)[0][3:]
                        self.key['name'] = cmd.split(',',4)[1][5:]
                        self.key['age'] = cmd.split(',',4)[2][4:]
                        self.key['salary'] = cmd.split(',',4)[3][7:]
                        self.Add()
                    else:
                        print('Student ID has been repeated and cannot continue to add updates')
                elif (cmd.startswith('update')):
                    cmd = cmd.replace('update','').lstrip()
                    if People.objects(ID=cmd.split(',')[0][3:]).count() != 0:
                        self.Update(cmd.split(',')[0][3:],cmd.split(',')[1:])
                    else:
                        print('There is no ID number you want to modify')
                elif (cmd.startswith('delete')) and (len(cmd.split()) == 2):
                    if People.objects(ID=cmd.split('=')[1]):
                        self.Delete(cmd.split('=')[1])
                    else:
                        print('Student number does not exist!')
                elif (cmd.startswith('show')) and (len(cmd.split()) == 2):
                    self.Showall()
                elif (cmd.startswith('select')) and (len(cmd.split()) == 2):
                    if People.objects(ID=cmd.split('=')[1]):
                        self.Select(cmd.split('=')[1])
                    else:
                        print('Student number does not exist!')
                else:
                    print('syntax error')

            except KeyboardInterrupt:
                print('\nbye')
                sys.exit(0)
    def Add(self):
        value = People(ID = self.key['id'],name=self.key['name'],age=self.key['age'],salary=self.key['salary'])
        if value:
            value.save() 
            print('  Successful!!  ')
        else:
            print('faild')

    def Select(self,value):
        dlist = People.objects.all()
        dlist = People.objects(ID=value)
        for each in dlist:
            print('ID号:{}\t姓名:{}\t年龄:{}\t收入:{}\t'.format(each.ID,each.name,each.age,each.salary))

    def Showall(self):
        for each in People.objects:
            print('ID号:{}\t姓名:{}\t年龄:{}\t收入:{}\t'.format(each.ID,each.name,each.age,each.salary))

    def Delete(self,value):
        idlist = People.objects(ID=value)
        if  idlist.delete():
            print('Successful!!!')
        else:
            print('Fiald')

    def Update(self,Id,value):
        modify = People.objects(ID=Id).first()  
        for i in range(len(value)):
            if value[i][:value[i].index('=')] == 'id':
                modify.ID = value[i][value[i].index('=')+1:] 
            elif value[i][:value[i].index('=')] == 'name':
                modify.name = value[i][value[i].index('=')+1:]
            elif value[i][:value[i].index('=')] == 'age':
                modify.age = value[i][value[i].index('=')+1:]
            elif value[i][:value[i].index('=')] == 'salary':
                modify.salary = value[i][value[i].index('=')+1:]
        print('Update Successful!!!')
        modify.save()

if __name__ == '__main__':
    MyMongoDB = Database()
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐