1、接上篇 《Mac OS 配置Docker+Mysql》,本地环境已配置完成 mysql,要想在使用python 操作mysql,还需要安装 mysql 库,使用命令:
pip3 install PyMySQL
2、在本地数据库建立库、表
3、导入 mysql 包
import pymysql
4、使用 python 连接数据库
db = pymysql.connect("127.0.0.1","root","123456","test" )
5、使用 cursor() 方法创建一个游标对象
cursor cursor = db.cursor()
6、实现新增
sql1 = """INSERT INTO Student(
S_Name,Address,City)
VALUES ('David','浙江','Beijing')"""
try:
# 执行sql语句
cursor.execute(sql1)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
7、实现查询
sql2="""select * FROM Student WHERE S_Name = 'David' """
try:
# 执行sql语句
cursor.execute(sql2)
# 提交到数据库执行
db.commit()
row=cursor.fetchone()
print (row)
except:
# 如果发生错误则回滚
db.rollback()
8、实现修改
sql3="""update Student Set S_Name = 'David2' where S_Name= 'David' """
try:
# 执行sql语句
cursor.execute(sql3)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
9、实现删除
sql4 = """DELETE FROM Student WHERE S_Name = 'David2' """
try:
# 执行sql语句
cursor.execute(sql4)
# 提交到数据库执行
db.commit( )
except:
# 如果发生错误则回滚
db.rollback()
10、最后需要关闭 db 连接
db.close()