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()
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()