mongoDB-python

from pymongo import *
def insert():
    try:
        #1.获取连接对象
        client=MongoClient(host='localhost',port=27017)
        #2.获取数据库以及集合对象
        db=client.python
        col=db.stu
        res=col.insert_many([{'name':'zhangsan','age':20},
                             {'name':'hanmeimei','age':18},
                             {'name':'lilei','age':25}
                             ])
        print(res)
    except Exception as e:
        print(e)
def select():
    try:
        #1.创建连接对象
        client=MongoClient(host='localhost',port=27017)
        #2.获取数据库以及集合对象
        db=client.python
        col=db.stu
        #查询一套记录的时候 返回的数据是一个字典
        #res=col.find_one()
        #print(r是一个cursor类型的对象,可以支持迭代遍历)
        #find()查找的结构
        res=col.find()
        for item in res:
            print(item['name'])
    except Exception as e:
        print(e)
def update():
    try:
        #1.创建连接对象
        client=MongoClient(host='localhost',port=27017)
        #2.获取数据库以及集合对象
        db=client.python
        #db.stu.update_one({'name':'zhangsan'},{'$set':{'name':'张三'}})
        db.stu.update_many({'name':'lilei'},{'$set':{'name':'李磊'}},{'multi':True})
        print('ok')
    except Exception as e:
        print(e)
def delete():
    try:
        client=MongoClient(host='localhost',port=27017)
        db=client.python
        db.stu.delete_one({'name':'lilei'})
        print('ok')
    except Exception as e:
        print(e)
def main():
    #insert()
    #update()
    #select()
    #delete()
    while True:
        txt=input('请输入要进行的操作:\n 1.查询, 2.增加, 3.修改, 4.删除, 5.退出 \n :')
        if txt=='1':
            select()
        elif txt=='2':
            insert()
            #pass
        elif txt=='3':
            update()
            #pass
        elif txt=='4':
            delete()
            #pass
        elif txt=='5':
            break
if __name__ == "__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值