目录结构
一、Python访问MySQL的相关操作
1. 创建数据库表
2. 向表中新增数据
3. 查询数据
4. 更新&删除数据
5. 事务&异常处理
二、日期格式、编码解码
1. 日期时间格式
2. Python字典与json互转
3. Python编码&解码
一、Python访问MySQL的相关操作
前提条件:
1)安装MySQL运行环境,如:PhpStudy
2)安装Python第三方包文件:pymysql
以Python3为例,需要安装 pymysql,如下:
pip install pymysql

1. 创建数据库表
py-mysql.py
import pymysql
# 连接数据库:主机地址、端口号;用户名&密码;数据库名
db=pymysql.Connect(host="localhost",port=3306,user="root",passwd="root",db="stu",charset="utf8")
cursor=db.cursor() # 创建游标对象
# 创建表
sql="""
CREATE TABLE student(
id int NOT NULL,
name varchar(20),
age int,
city varchar(32))
"""
cursor.execute(sql) # 执行以上sql语句,实现创建数据表
db.close() # 关闭数据库连接
查看所创建的表&表结构:

2. 向表中新增数据
insert-db.py
import pymysql
# 连接数据库:主机地址、端口号;用户名&密码;数据库名
db=pymysql.Connect(host="localhost",port=3306,user="root",passwd="root",db="stu",charset="utf8")
cursor=db.cursor() # 创建游标对象
# 向数据表中增加数据
sql="""
INSERT INTO student(id,name,age,city)
VALUES
(1,"AAA",16,"Shanghai"),
(2,"BBB",18,"Chengdu"),
(3,"CCC",21,"Guangdong");
"""
cursor.execute(sql) # 执行以上sql语句
db.commit() # 提交使新增数据到数据库
db.close() # 关闭数据库连接

3. 查询数据
select-db.py
import pymysql
# 连接数据库:主机地址、端口号;用户名&密码;数据库名
db=pymysql.Connect(host="localhost",port=3306,user="root",passwd="root",db="stu",charset="utf8")
cursor=db.cursor() # 创建游标对象
# 查询数据表中的数据
sql="""
SELECT * FROM student;
"""
cursor.execute(sql) # 执行以上sql语句
data1=cursor.fetchone() # 获取单个对象(一行数据)
data2=cursor.fetchall() # 获取所有对象(多行数据)
print(data1)
print("----------------------------")
print(data2)
db.close() # 关闭数据库连接

4. 更新&删除数据
(1)更新数据
update-db.py
import pymysql
# 连接数据库:主机地址、端口号;用户名&密码;数据库名
db=pymysql.Connect(host="localhost",port=3306,user="root",passwd="root",db="stu",charset="utf8")
# 创建游标对象
cursor=db.cursor()
# 修改数据表中的数据
sql="""
UPDATE student SET age=age+1;
"""
cursor.execute(sql) # 执行以上sql语句
db.commit() # 提交使更新数据库生效
db.close()

(2)删除数据
delete-db.py
import pymysql
# 连接数据库:主机地址、端口号;用户名&密码;数据库名
db=pymysql.Connect(host="localhost",port=3306,user="root",passwd="root",db="stu",charset="utf8")
# 创建游标对象
cursor=db.cursor()
# 删除数据表中的数据
sql="""
DELETE FROM student WHERE name="CCC";
"""
cursor.execute(sql) # 执行以上sql语句
db.commit() # 提交使更新数据库生效
db.close()

5. 事务&异常处理
前提条件:事务支持需要MySQL的存储引擎为InnoDB,而MyISAM不支持事务
事务:一个事务作为一个不可分割的整体,事务中的一组操作命令全部执行or全部都不执行
回滚:所有操作都不提交
- 查看引擎
# 查看MySQL当前提供的存储引擎
show engines;
# 查看某个表使用的引擎
show create table xx表名;
- 修改表的存储引擎
# 直接修改表的存储引擎
ALTER TABLE xx表名 ENGINE=InnoDB;
# 创建新表(结构同旧表),并将存储引擎修改为InnoDB
CREATE TABLE 新表名 LIKE 旧表名;
ALTER TABLE 新表名 ENGINE=InnoDB;
# 查询旧表中的数据插入到新表中
INSERT INTO 新表名 SELECT * FROM 旧表名;
修改表引擎后查看存储引擎:

transaction.py
import pymysql
# 连接数据库:主机地址、端口号;用户名&密码;数据库名
db=pymysql.Connect(host="localhost",port=3306,user="root",passwd="root",db="stu",charset="utf8")
cursor=db.cursor() # 创建游标对象
# 多个SQL事务(全部执行or全部不执行)
sql1="INSERT INTO student VALUES(2,'BBB',23,'Hangzhou')"
sql2="DELETE * FROM student WHERE uid=1;"
# 异常处理
try:
cursor.execute(sql1)
cursor.execute(sql2)
db.commit() # 提交事务
except Exception as e:
db.rollback() # 回滚(撤销上一操作,所有操作都不提交)
print("操作异常,已作回滚处理!")
db.close() # 关闭数据库连接
执行结果:


二、日期格式、编码解码
1. 日期时间格式
date.py
import datetime
# 获取当前日期
date1=datetime.datetime.now()
# 获取一个指定的日期
date2=datetime.datetime(2020,1,2,11,15,22)
# 日期转字符串
date3=date1.strftime("%Y-%m-%d %H:%M:%S")
# 字符串转日期
s="2020-11-11 00:00:00"
date4=datetime.datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
print(date1)
print(date2)
print(date3)
print(date4)

2. Python字典与json互转
json:作为js中的对象,本质上json是具有特定结构的字符串,如:{key1:value1,key2:value2...},在Python中类似字典结构,可以相互进行转换
作用:json可在不同系统进行数据传递,or在同一系统的前端和后端进行数据传递
json.py
import json
# json转字典
j1='{"id":"001","name":"AAA","city":"广州"}'
p=json.loads(j1)
print(p)
print(type(p))
print("---------------------")
# 字典转json
j2=json.dumps(p,ensure_ascii=False) # 转换后汉字不以ASCII码展示
print(type(j2))
print(j2)
print("---------------------")
j3=json.dumps(p) # 汉字默认以ASCII码格式展示
print(j3)

3. Python编码&解码
Python3中字符串的两种类型:bytes,str。bytes存储byte类型(二进制),str存储Unicode类型(字符串)
编码:str ==> bytes
解码:bytes ==> str
encode-decode.py
# 编码:字符串==>byte
s1="测试字符串"
b=s1.encode("utf-8") # 转为字节码
print(b)
# 解码:byte==>字符串
s2=b.decode("utf-8")
print(s2)
PS:以上,编码方式和解码方式需要对应一致,如都同为 utf-8 或 gbk

网友评论