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)
相关推荐
Yvonne爱编码6 分钟前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
前端摸鱼匠1 小时前
YOLOv8 环境配置全攻略:Python、PyTorch 与 CUDA 的和谐共生
人工智能·pytorch·python·yolo·目标检测
WangYaolove13141 小时前
基于python的在线水果销售系统(源码+文档)
python·mysql·django·毕业设计·源码
AALoveTouch1 小时前
大麦网协议分析
javascript·python
ZH15455891311 小时前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh2 小时前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh2 小时前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics
YongCheng_Liang2 小时前
从零开始学 Python:自动化 / 运维开发实战(核心库 + 3 大实战场景)
python·自动化·运维开发
鸽芷咕2 小时前
为什么越来越多开发者转向 CANN 仓库中的 Python 自动化方案?
python·microsoft·自动化·cann
秋邱2 小时前
用 Python 写出 C++ 的性能?用CANN中PyPTO 算子开发硬核上手指南
开发语言·c++·python