python操作数据库
一、python操作MySQL
1.PyMySQL介绍
PyMySQL是一个纯python的MySQL客户端库,它大多数API都兼容了mysqlclient
, MySQLdb
-
版本支持:
python 2.7 ,3.5+
MySQL server 5.5 +
-
安装:
pip install pymysql
-
官方文档:
https://pymysql.readthedocs.io/en/latest/
-
连接前准备工作:
设置端口映射,mysql服务默认监听3306,设置虚拟机3306端口映射物理机的3306端口
使用develop 用户 账号:
develop
密码:QWEqwe123
2.简单使用
import pymysql
# 套路,步骤
# 1. 创建连接
conn = pymysql.connect(
host='127.0.0.1', # 主机
port=3306, # 端口
user='develop', # 用户名
password='QWEqwe123', # 密码
db='zzh', # 数据库
charset='utf8' # 字符编码
)
# 2. 创建游标
# 通过指定cursor的构造类,返回不同形式的结果
# cursor = conn.cursor() # 默认返回元组形式的结果
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 返回字典形式的结果
# 3. 执行sql语句
cursor.execute('select name as aaa from student')
# 4.获取结果
res = cursor.fetchall() # 获取所有行
print(res)
# 5.关闭游标
cursor.close()
# 6.关闭连接
conn.close()
**********************************************************************
[{'aaa': 'zs'}, {'aaa': 'ls'}, {'aaa': 'ww'}, {'aaa': 'zl'}, {'aaa': 'zmz'}]
3.使用pymysql进行查询
# 4.获取结果
# cursor 中的数据流,所有结果只能被读一次,前面已经获取了的数据,后面无法获取到
res1 = cursor.fetchone() # 获取一行 返回的是 一条数据 字典,元组
print('获取一条')
print(res1)
res2 = cursor.fetchmany(2) # 获取几行 返回的是 多条数据 列表
print('获取两条')
print(res2)
res = cursor.fetchall() # 获取所有行
print('获取剩下所有的')
print(res)
res3 = cursor.fetchone()
print(res3) # None
4.使用pymysql进行增删改
import pymysql
# 套路,步骤
# 1. 创建连接
conn = pymysql.connect(
host='127.0.0.1', # 主机
port=3306, # 端口
user='develop', # 用户名
password='QWEqwe123', # 密码
db='zzh', # 数据库
charset='utf8', # 字符编码
cursorclass=pymysql.cursors.DictCursor # 传入conn.cursor()的参数
)
# 2. 创建游标
# pymysql 默认支持事务
try:
with conn.cursor() as cursor:
# 3.构建 sql语句 动态
from_name = input('请输入转账账户名>>>>:')
to_name = input('请输入转入账户名>>>>:')
money = int(input('请输入转账金额>>>>>:'))
# 直接拼接的方法不推荐,会发生sql注入
# sql1 = 'update account set money=money-%s where name="%s"' % (money, from_name)
sql1 = 'update account set money=money-%s where name=%s'
sql2 = 'update account set money=money+%s where name=%s'
# 4.执行sql语句
cursor.execute(sql1, args=(money, from_name)) # 传递参数
cursor.execute(sql2, args=(money, to_name))
# 5. 提交事务
conn.commit()
except Exception as e:
# 有异常
print(e)
# 6.处理异常,并回滚
conn.rollback() # 回滚
finally:
# 7. 关闭连接
conn.close()
二、python操作Redis
1.redis-py介绍
redis-py是键值数据库redis的python实现接口
两个大版本,2.x, 3.0。3.0有很多新特效,使用的时候需要做兼容处理
-
版本支持:
3.0:python2.7,python3.4+
-
安装:
pip install redis
不要
sudo
安装,推荐安装在virtualenv
-
官方文档:
https://redis-py.readthedocs.io/en/latest/
-
连接前的准备工作:
设置端口映射 ,redis服务默认监听6379,设置虚拟机6379端口映射物理机的6379端口
2.redis-py 操作redis
python 操作redis的命令和命令行几乎一致,除了del
,因为和关键字重名,用delete代替
import redis
# 套路
# 1.建立连接
# conn = redis.Redis( # StrictRedis、pipelines都是它的子类
# host='127.0.0.1', # localhost
# port=6379,
# db=0
# )
conn = redis.StrictRedis( # 兼容旧版本(推荐使用)
host='127.0.0.1', # localhost
port=6379,
db=0,
decode_responses=True # 设置为True返回的数据格式就是str类型,在程序操作的数据默认为bytes类型
)
# key 的操作
res = conn.keys('*') # 查看所有key
print(res)
print(conn.delete('Name')) # 删除数据
print(conn.keys('*'))
# conn.set(key, value) # 新建数据
3.piplines
管道是redis类的子类, 它支持在一个请求中缓冲多个命令到服务器
import redis
conn = redis.StrictRedis(
host='127.0.0.1', # localhost
port=6379,
db=0,
decode_responses=True
)
# 创建一个管道
pipe =conn.pipeline()
# 缓冲两条命令
pipe.keys('*')
pipe.set('name', 'zzh')
# 执行命令
res = pipe.execute()
print(res[0])
print(res[1])
三、python操作MongDB
1.PyMongo介绍
-
版本支持:
python2.7,3.4+
-
安装:
pip install pymongo
-
官方文档:
-
连接前的准备工作:
-
设置端口映射,虚拟机27017端口映射到物理机27017
-
修改,
sudo vim /etc/mongodb.conf
配置文件中的bind_ip = 0.0.0.0
-
重启mongo服务
service mongodb restart
2. 简单使用
import pymongo
# 套路
# 1.创建连接
client = pymongo.MongoClient(host='127.0.0.1', port=27017)
# 获取所有数据库
databases = client.list_database_names() # 返回一个列表
print(databases)
# 2.选择/创建数据库 不存在则创建
db = client['school'] # => client.school
# 3.选择/创建集合
collection = db['student'] # => db.student
# 获取所有的集合
cols = db.collection_names()
print(cols)
3.文档操作
(1).添加数据
# 1.插入一个文档
doc = {'name': 'zzh', 'age': 18}
insert_id = collection.insert_one(doc).inserted_id
# 2.插入多个文档
docs = [
{'name': 'zzh', 'age': 18},
{'name': 'dx', 'age': 19},
{'name': 'sz', 'age': 20},
{'name': 'ssl', 'age': 21},
]
insert_ids = collection.insert_many(docs).inserted_ids
print(insert_ids)
(2).查询数据
# 2.查询文档
# 1.查询一条,只想取匹配到的第一条
one = collection.find_one({'age': {'$gt': 18}})
# print(one)
# 2.查询所有
all_docs = collection.find()
# for doc in all_docs: # all_docs是一个游标对象,需要迭代取出数据
# print(doc)
# docs = [x for x in all_docs]
# print(all_docs)
# 3.查询指定字段
docs = collection.find({}, {'name': 1, 'age': 1})
# for doc in docs:
# print(doc)
# 4.limit,skip
docs = collection.find().limit(3).skip(3)
# for doc in docs:
# print(doc)
# 5.排序
# 1.单字段排序
docs = collection.find({}, {'age': 1}).sort('age', -1)
# for doc in docs:
# print(doc)
# 2.多字段排序
docs = collection.find({}, {'age': 1, 'name': 1}).sort([
('age', -1),
('name', 1)
])
for doc in docs:
print(doc)
(3).更新
# 更新
# 1.全文档替换
# doc = {'name': 'zzh', 'age': 16}
# res = collection.replace_one({}, doc) # upsert参数可选,如果设置为True,匹配不到数据就插入
# print(res.matched_count, res.modified_count, res)
# 2.修改一条
# res = collection.update_one({}, {'$set': {'name': 'zhihao'}})
# print(res.matched_count, res.modified_count, res)
# 3.修改多条
# res = collection.update_many({'name': 'zzh'}, {'$set': {'name': 'zhihao'}})
# print(res.matched_count, res.modified_count, res)
(4).删除文档
# 删除
# 1.删一条
# res = collection.delete_one({})
# print(res.raw_result, res.deleted_count)
# 2.删多条
# res = collection.delete_many({'name': 'zhihao'})
# print(res.raw_result, res.deleted_count)
(5).聚合与分组
## 聚合与分组
pipline = [
{'$group': {'_id': '$sex', 'count': {'$sum': 1}}},
{'$sort': {'count': -1}}
]
res = collection.aggregate(pipline)
for item in res:
print(item)