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('登录失败')
相关推荐
洗紫39 分钟前
Python中的条件语句怎么使用?
python
南汐汐月1 小时前
重生归来,我要成功 Python 高手--day35 深度学习 Pytorch
pytorch·python·深度学习
java1234_小锋1 小时前
[免费]基于Python的深度学习豆瓣电影数据可视化+情感分析推荐系统(Flask+Vue+LSTM+scrapy)【论文+源码+SQL脚本】
python·信息可视化·flask·电影数据可视化
PieroPc2 小时前
一个基于Python Streamlit sqlite3 的销售单管理系统,提供商品管理、客户管理、销售单管理及打印,和应收对账单等功能
python·oracle·sqlite·streamlit
月下倩影时2 小时前
视觉进阶篇—— PyTorch 安装
人工智能·pytorch·python
Valueyou242 小时前
论文阅读——CenterNet
论文阅读·python·opencv·目标检测·计算机视觉
孤狼warrior2 小时前
目前最新同花顺金融股市数据爬取 JS逆向+node.js补浏览器环境
javascript·爬虫·python·金融·node.js
蒋星熠2 小时前
全栈开发实战指南:从架构设计到部署运维
运维·c++·python·系统架构·node.js·devops·c5全栈
程序员爱钓鱼3 小时前
Python 编程实战 · 实用工具与库 — Flask 基础入门
后端·python·面试
程序员爱钓鱼3 小时前
Python编程实战 - Python实用工具与库 - 文件批量处理脚本
后端·python·面试