1. Python 与Mysql的交互
首先python 与 mysql的交互要依赖于第三方模块pymysql,所有先安装pymysql
pip install pymysql
然后实现用python 链接mysql数据库
import pymysql #链接数据库 db=pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123",db="test") #创建光标 cur=db.cursor() sql='select * from test1' #执行sql语句 cur.excute(sql) #当sql语句不是查询时需要执行下面的提交命令 #db.commit() cur。close() db.close()
#在此sql语句就不在一一列举了
2 Python 与Mongodb的交互
同样python 与mongodb的交互要依赖于第三方模块pymongo,所有先安装pymongo
pip install pymongo
然后实现用python 链接mongodbl数据库
from pymongo import MongoClient # 连接MongoDB数据库 db = MongoClient('192.168.52.128', 27017) # 数据库的添加 my_db = db.my_db # 创建文件 my_info = my_db.my_info # 向文件中插入数据 # my_info.insert([{'name': '曙光', 'age': 30, 'sex': '男'},{'name': '冰封', 'age': 15, 'sex': '男'},{'name': '哈哈', 'age': 18, 'sex': '男'},{'name': '嗝', 'age': 20, 'sex': '男'},{'name': '李坤', 'age': 28, 'sex': '女'}]) ''' insert():可以实现单条或多条数据的插入 save():只能完成单条数据的插入,并且数据必须是字典结构 ''' # 查询数据 res = my_info.find({'name': 'xiaocaicai'}) for item in res: print(item) 更新数据 #multi:布尔类型设置数据更新时是否一次性更新多条数据,默认为False # upsert:设置数据更新时如果数据不存在,是否将本次数据添加到文件中,默认为False my_info.update({'name': 'xiaocai'}, {'$set': {'age': 20, 'sex': '女'}}, multi=True, upsert=True) # 删除数据 delete_one():删除数据库中一条数据 delete_many():一次性删除多条数据 my_info.delete_one({'name': 'xiaocai'}) my_info.delete_many({'name': 'xiaocai',{'name': 'xixx'}) # mongodb查询 ''' > : $gt < : $lt >= : $gte <= : $lte ''' # 查询年龄在[15,25]之间的数据 res = my_info.find({'age': {'$gte': 15, '$lte': 25}}) for item in res: print(item) # 查询年龄在15岁以下,或25岁以上的人员 res = my_info.find({'$or': [{'age': {'$lte': 15}}, {'age': {'$gte': 25}}]}) for item in res: print(item) res = my_info.find({'$or': [{'age': {'$lte': 15}}, {'age': {'$gte': 25}}], 'name': 'xiaocaicai'}) for item in res: print(item) # $or: 或者,该指令通常作为字典的键,其对应的值是一个列表结构,列表中的每一个元素之间是并列的关系 # 在字典中所有的键值对之间是一种并且的关系 res = my_info.find({'$or': [{'age': {'$gte': 10, '$lte': 15}}, {'age': {'$gte': 25, '$lte': 30}}], 'name': 'xiaocaicai'}) # # sort():将查找之后的结果按照指定的字段进行排序,1代表升序,-1代表降序 # # skip(n):跳过n条数据之后再提取数据 # # limit(m):限定从某一个位置开始,只提取m条数据 res = res.sort('age', -1).skip(1).limit(2) for item in res: print(item) # $in:提取在指定内容中的数据 res = my_info.find({'age': {'$in': (10, 20, 30, 25)}}) for item in res: print(item) obj = {'name': '冰哥', 'age': '18', 'sex': '女', 'photo': ['img/big.jpg', 'img/small.jpg', 'img/normal.jpg'], 'score': [20, 30, 50, 12]} my_info.insert(obj) # all:查找对应的数据库中的某一条数据是否包含all中所有的值,如果满足则返回结果,如果不满足则不返回数据 res = my_info.find({'score': {'$all': [20, 30]}}) for item in res: print(item) # $push:向已有数据源中按照字段进行数据的添加 my_info.update({'name': '冰哥'}, {'$push': {'score': [100, 150]}}) # $pop:将数据库中对应数据的某一个字段数据按照指定方式进行删除,-1:从列表的起始位置开始删除,1:从列表的最后位置开始删除 my_info.update({'name': '冰哥'}, {'$pop': {'score': -1}}) # $pull:将对应数据中指定的数据分布进行删除(按值删除) my_info.update({'name': '冰哥'}, {'$pull': {'score': [100, 150]}}) # 多路查询 res = my_info.find({'score.0': 50}) for item in res: print(item)