advPython-4

pymysql 模块

python 复制代码
import pymysql

# 连接数据库
conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123',
    database='db1',
    charset='utf8',
    cursorclass=pymysql.cursors.DictCursor  # cursor=pymysql.cursors.DictCurosr:将查询结果以字典的形式返回
)

cursor = conn.cursor()  # 产生一个游标对象

res = cursor.execute('select * from emp;')  # 返回值为当前sql语句影响的行数,一般不用
# print(res)

# 获取命令执行的查询结果
# print(cursor.fetchone())  # 拿到一条

# 读取数据类似于文件的光标的移动
print(cursor.fetchone())
print(cursor.fetchone())
# cursor.scroll(1, 'relative')  # 相对移动
cursor.scroll(5, 'absolute')  # 绝对移动
print(cursor.fetchone())

pymysql 补充

python 复制代码
import pymysql

conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123',
    database='db1',
    charset='utf8',
    cursorclass=pymysql.cursors.DictCursor,
    autocommit=False  # 控制是否开启--自动提交操作--模式
)

cursor = conn.cursor()

# # 增
# sql = 'insert into dep(id,name) values(%s,%s)'
# rows = cursor.execute(sql, ('204', '管理部'))
# # rows = cursor.executemany(sql,[('205','监督部'),('206','法律部'),(),(),()...])  # 一次添加多个数据
# print(rows)
# conn.commit()  # 提交操作

# # 修改
# sql = 'update emp set name="jasonNB" where id=1'
# rows = cursor.execute(sql)
# print(rows)
# conn.commit()  # 提交操作

# 删除
# sql = 'delete from dep where id=204'
# rows = cursor.execute(sql)
# print(rows)
# conn.commit()  # 提交操作

# # 查询
# sql = 'select * from emp where id>3'
# rows = cursor.execute(sql)
# print(rows)
# for i in cursor.fetchall():
#     print(i)

"""
补充知识:
对数据库的增删改是非常严肃的问题,使用需要人为再确认才能真正生效!-> conn.commit() # 提交操作 或者 开启自动提交操作模式
而对应查操作,直接执行!
"""

sql 注入问题

python 复制代码
import pymysql

# 连接数据库
conn = pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123',
    database='db1',
    charset='utf8',
    cursorclass=pymysql.cursors.DictCursor
)

cursor = conn.cursor()
while 1:
    usename = input('名字>>>')
    id = input('ID>>>')
    sql = "select * from emp where name=%s and id=%s"
    # 不要自己做拼接,用%占位即可,然后让execute帮忙检查是否合法同时它会自动拼接
    rows = cursor.execute(sql, (usename, id))
    if rows:
        print('登录成功!')
    else:
        print('登录失败')
相关推荐
wuyk5553 小时前
Python办公自动化-第01讲-环境搭建与自动化认知
python·自动化·pyqt
高洁014 小时前
数字孪生与计算机视觉:让机器看懂现场
人工智能·python·机器学习·transformer·迁移学习
ComPDFKit4 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
yz_aiks5 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
2601_967980117 小时前
Flask Web 应用
python·flask·web开发·环境变量·虚拟环境
aifannihao7 小时前
ß 大写变 SS:用 Python 算清 Ruby2Shell 的缓冲区账本
python·安全·标准库·缓冲区溢出·字符串编码
liwulin05068 小时前
【OLLAMA】调用SKILL的通用ReAct
python
郝学胜-神的一滴8 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
Norna10 小时前
Git 给路径加了引号,这个文件就从 review 里消失了
python
wuyk55510 小时前
Python办公自动化-第04讲-批量新建Excel
开发语言·python·excel