打开cmd利用pip3 install pymysql -i https://pypi.doubanio.com/simple 进行安装
包括数据库的链接,增删查改
import pymysql # 导入 pymysql
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root",password="123456", db="test5", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
# 1.查询操作
# 编写sql 查询语句 user 对应我的表名
sql = "select * from user"
sql_insert ="""insert into user(username,password) values('liu','1234')"""
sql_update ="update user set username = '%s' where id = %d"
sql_delete ="delete from user where id = %d"
try:cur.execute(sql) # 执行sql语句results = cur.fetchall() # 获取查询的所有记录print("id", "username", "password")# 遍历结果for row in results:id = row[0]name = row[1]password = row[2]print(id, name, password)cur.execute(sql_update % ("xiongda", 3)) # 像sql语句传递参数,执行更新操作cur.execute(sql_insert) # 执行插入操作cur.execute(sql_delete % (3)) # 像sql语句传递参数,执行删除操作db.commit() #数据库插入提交
except Exception as e:db.rollback()raise e
finally:db.close() # 关闭连接
(mysql数据库需要配置环境变量。用navicat进行界面展示。)
参考自https://blog.csdn.net/qq_37176126/article/details/72824106