PyMySQL 笔记

安装

复制代码
pip install pymysql

查询

py 复制代码
import pymysql

# 连接数据库
connect = pymysql.connect(host='localhost', port=3306, user='root', password='1234', db='send',
                          charset='utf8')
# 获取游标
cursor = connect.cursor()

# 执行sql
sql = "select * from employee"
cursor.execute(sql)

# 获取结果,fetchall 全部,fetchone 一行,fetchmany 多行
result = cursor.fetchone() # 返回是一个元组

print(result)

# 关闭连接
cursor.close()
connect.close()

新增

py 复制代码
import pymysql

# 连接数据库
connect = pymysql.connect(host='139.129.233.191', port=3306, user='root', password='ch201688', db='cable',
                          charset='utf8')
# 获取游标
cursor = connect.cursor()

# 执行sql
sql = "insert into employee values(1, 'Tom', 10, 5000)"
result = cursor.execute(sql)

if result:
    connect.commit()  # 提交
else:
    connect.rollback()  # 回滚

print(result)  # 1,表示受影响行数

# 关闭连接
cursor.close()
connect.close()

防止SQL注入

使用 %s 预编译

py 复制代码
# 获取游标
cursor = connect.cursor()

# 执行sql
sql = "select * from user where username = %s and password = %s"
# 参数化
params = ('admin', 'admin')
cursor.execute(sql, params)
相关推荐
花酒锄作田11 小时前
Pydantic校验配置文件
python
hboot11 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python