mongodb数据库的连接,需要先导入pymongo库,然后使用它的MongoClient方法进行连接,具体的操作方法详见mian函数中的代码,基本的CURD操作详见各个函数
from pymongo import MongoClient
import pymongo
def delete_contacter_info(coll):
name = input('请输入想要删除的联系人姓名:')
coll.delete_one({'conname': name})
def update_contacter_info(coll):
name = input('请输入想要更新联系人的姓名')
newname = input('请输入新的姓名:')
newtel = input('请输入新的联系方式:')
newemail = input('请输入新的邮箱地址')
coll.update_one({'conname': name}, {"$set": {'conname': newname, 'contel': newtel, 'conemail': newemail}})
def find_all_contacters(coll):
print('编号'.rjust(4, ' '), '姓名'.rjust(9, ' '), '电话'.rjust(11, ' '), '邮箱'.rjust(11, ' '))
for index, contacter in enumerate(coll.find()):
name = contacter['conname']
tel = contacter['contel']
email = contacter['conemail']
print(str(index).rjust(4, ' '), name.rjust(9, ' '), tel.rjust(11, ' '), email.rjust(11, ' '))
choice = input('是否需要更新联系人信息:yes|no')
if choice.lower() == 'yes':
update_contacter_info(coll)
else:
choice = input('是否需要删除联系人信息?yes|no')
if choice.lower() == 'yes':
delete_contacter_info(coll)
def find_contacters_by_name(coll):
name = input('请输入想要查找的联系人姓名:')
print('编号'.rjust(4, ' '), '姓名'.rjust(9, ' '), '电话'.rjust(11, ' '), '邮箱'.rjust(11, ' '))
for index, contacter in enumerate(coll.find({'conname': name})):
name = contacter['conname']
tel = contacter['contel']
email = contacter['conemail']
print(str(index).rjust(4, ' '), name.rjust(9, ' '), tel.rjust(11, ' '), email.rjust(11, ' '))
choice = input('是否需要更新联系人信息?yes|no')
if choice == 'yes':
update_contacter_info(coll)
else:
choice = input('删除联系人?yes|no')
if choice.lower() == 'yes':
delete_contacter_info(coll)
def input_contacter_info():
name = input('联系人姓名:')
tel = input('联系人电话:')
email = input('联系人邮箱:')
return name, tel, email
def add_new_contacter(coll):
name, tel, email = input_contacter_info()
coll.insert_one({'conname': name, 'contel': tel, 'conemail': email})
print("插入成功!!!")
def find_contacters(coll):
while True:
print('1.查看所有联系人')
print('2.搜索联系人')
print('3.退出查找')
choice = int(input('请输入你的选择:'))
if choice == 1:
find_all_contacters(coll)
elif choice == 2:
find_contacters_by_name(coll)
elif choice == 3:
break
else:
print('输入错误,请从新选择!!!')
def main():
client = pymongo.MongoClient('mongodb://47.115.130.16:7788')
try:
db = client.address_book
coll = db.contacters
while True:
print('🐟🐟🐟🐟🐟🐟🐟🐟🐟通信录🐟🐟🐟🐟🐟🐟🐟🐟🐟')
print('❀ 1.新建联系人 ❀')
print('❀ 2.搜索联系人 ❀')
print('❀ 3.退出查找 ❀')
print('🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟')
choice = int(input("请输入你的选择:"))
if choice == 1:
add_new_contacter(coll)
elif choice == 2:
find_contacters(coll)
elif choice == 3:
break
else:
print('输入错误重新按照下方选择项,重新选择!!!!')
finally:
client.close()
if __name__ == '__main__':
main()