1. python操作MySQL
1.1 MySQL基础
在java基础部分就写过了。
1.2 pymysql模块
我在python基础部分已经写过pymysql了。
2. python操作MongoDB
2.1 MongoDB基础
2.2 pymongo模块
2.2.1 安装pymongo
pip install pymongo -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
2.2.2 连接MongoDB
importpymongo#获取连接的对象,两种连接方式都可以
client = pymongo.MongoClient('127.0.0.1',port=27017)#client = pymongo.MongoClient('mongodb://localhost:27017/')#获取数据库
db =client.newdb#获取集合(表)
collection =db.stu#插入一条数据到集合中
collection.insert_one({"name":"xhh","gender":"true","age":"20"})
结果:
2.2.3 操作MongoDB
操作MongoDB的主要方法如下:
(1) insert_one:加入一条文档数据到集合中。
collection.insert_one({"name":"xhh","gender":"true","age":"20"})
(2) insert_many:加入多条文档数据到集合中。
collection.insert_many([
{"name":"lx","gender":"true","age":"18"},
{"name":"lh","gender":"true","age":"20"}
])
结果:
(3) 查找一条文档对象。
result =collection.find_one()print(result)
(4) 查找所有文档对象。
cursor =collection.find()for x incursor:print(x)
结果:
(5) 更新一条文档对象。
collection.update_one({"name":"lx"},{"$set":{"age":"10"}})
(6) 更新多条文档对象。
collection.update_many({"gender":"true"},{"$set":{"age":"30"}})
更新前:
更新后:
(7) 删除一条文档对象。
collection.delete_one({"name":"xhh"})
结果:
因为我创建的是固定集合,不能删除文档。
(8) 删除多条文档对象。
collection.delete_many({"name":"xhh"})
结果: