Python知识分享第二十九天-PyMySQL

PyMySQL介绍:

复制代码
概述:
    它是Python的1个库(模块), 可以实现通过Python代码, 操作MySQL数据库.
    该库需要手动安装一下.
安装方式:
    方式1: 导包时自动安装.
    方式2: 在PyCharm的Settings -> Python编辑器或者Anaconda -> 安装
    方式3: 通过pip方式, 在命令行中安装.
        pip install pymysql -i 镜像地址
        例如:
            阿里云镜像:   https://mirrors.aliyun.com/pypi/simple/
            清华大学镜像: https://pypi.tuna.tsinghua.edu.cn/simple
操作步骤:
	1.获取连接对象
	2.根据连接对象 获取游标对象
	3.执行SQL语句 获取结果集
	4.操作结果集
	5.释放资源
细节:
	**如果操作的是更新语句(增删改),记得  提交(事务)**
python 复制代码
# 导包
import pymysql
# 1.获取连接对象 传入 数据库地址 端口号 用户名 密码 数据库名称 编码方式
conn = pymysql.connect(
    host='127.0.0.1',
    user='root',
    password='123456',
    database='db2',
    port=3306,
    charset='utf8'
)
# print(conn)
# 2.根据连接对象 获取游标对象
cursor = conn.cursor()
# 3.执行SQL语句 获取结果集
sql = 'select * from areas;'
cursor.execute(sql)
data = cursor.fetchall()  # 元组套元组
# 4.操作结果集
for row in data:
    print(row)
# 5.释放资源
cursor.close()
conn.close()

案例: PyMysql操作表数据, CURD操作.

细节: 如果操作更新语句(增删改), 记得: 提交事务(相当于把结果保存)

python 复制代码
import pymysql

def demo01_增():
    #  1. 获取连接对象.
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        database='db2',
        port=3306,
        charset='utf8'
    )
    #  2. 根据连接对象, 获取游标对象.
    cursor = conn.cursor()
    #  3. 执行SQL语句, 获取结果集.
    sql = "insert into areas values (999999,'天龙族',99999);"
    result = cursor.execute(sql)
    print(f'受影响的行数: {result}')
    #  4. 操作结果集.
    if result != 0:
        conn.commit()
        print('添加成功')
    else:
        conn.rollback() # 事务回滚, 把数据还原到SQL执行前的状态, 类似于Linux的快照.
     #  5. 释放资源.
    cursor.close()
    conn.close()
def demo02_删():
    #  1. 获取连接对象.
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        database='db2',
        port=3306,
        charset='utf8'
    )
    #  2. 根据连接对象, 获取游标对象.
    cursor = conn.cursor()
    #  3. 执行SQL语句, 获取结果集.
    sql = "delete from areas where id = 999999;"
    result = cursor.execute(sql)
    print(f'受影响的行数: {result}')
    #  4. 操作结果集.
    if result != 0:
        conn.commit()
        print('删除成功')
    else:
        conn.rollback() # 事务回滚, 把数据还原到SQL执行前的状态, 类似于Linux的快照.
     #  5. 释放资源.
    cursor.close()
    conn.close()

def demo03_改():
    #  1. 获取连接对象.
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        database='db2',
        port=3306,
        charset='utf8'
    )
    #  2. 根据连接对象, 获取游标对象.
    cursor = conn.cursor()
    #  3. 执行SQL语句, 获取结果集.
    sql = "update areas set title = '龙族' where id=999999"
    result = cursor.execute(sql)
    print(f'受影响的行数: {result}')
    #  4. 操作结果集.
    if result != 0:
        conn.commit()
        print('修改成功')
    else:
        conn.rollback() # 事务回滚, 把数据还原到SQL执行前的状态, 类似于Linux的快照.
     #  5. 释放资源.
    cursor.close()
    conn.close()


def demo04_查():
    #  1. 获取连接对象.
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123456',
        database='db2',
        port=3306,
        charset='utf8'
    )
    #  2. 根据连接对象, 获取游标对象.
    cursor = conn.cursor()
    #  3. 执行SQL语句, 获取结果集.
    sql = "select * from areas where id=999999"
    cursor.execute(sql)
    result = cursor.fetchall()
    #  4. 操作结果集.
    for row in result:
        print(row)
     #  5. 释放资源.
    cursor.close()
    conn.close()


if __name__ == '__main__':
    demo01_增()
    # demo02_删()
    demo03_改()
    demo04_查()

需求: 模拟登陆, 接收用户录入的账号和密码, 然后判断.

这种写法会有sql注入问题 例如用户输入: 随便' or '1=1

这个时候所有的数据都会被查到

python 复制代码
# 需求: 模拟登陆, 接收用户录入的账号和密码, 然后判断.


# 导包
import pymysql

# 1. 提示用户录入他/她的账号或者密码, 并接收.
uname = input('请录入您的账号: ')
pwd = input('请录入您的密码: ')

try:
    # 2. 连接数据库, 获取游标.
    conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='day03', charset='utf8')
    cursor = conn.cursor()

    # 3. 定义SQL语句.
    # sql = f"select * from users where username='{uname}' and password='{pwd}';"
    sql = "select * from users where username='%s' and password='%s';" % (uname, pwd)

    # 4. 执行SQL语句, 获取结果集, 判断是否登录成功.
    cursor.execute(sql)
    result = cursor.fetchone()
    if result:
        print('登录成功!')
    else:
        print('登陆失败!')
finally:
    # 5. 关闭游标和数据库连接, 释放资源.
    cursor.close()
    conn.close()

需求: 模拟登陆, 接收用户录入的账号和密码, 然后判断.

解决思路: 预编译思想, 即: 预先对SQL语句做编译, 此时已经确定了SQL语句的格式, 之后无论传入什么内容, 都只会当做普通的字符来处理.

python 复制代码
# 导包
import pymysql

# 1. 提示用户录入他/她的账号或者密码, 并接收.
uname = input('请录入您的账号: ')
pwd = input('请录入您的密码: ')

try:
    # 2. 连接数据库, 获取游标.
    conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='day03', charset='utf8')
    cursor = conn.cursor()

    # 3. 定义SQL语句.
    # 拼接思路, 会发生SQL注入攻击.
    # sql = "select * from users where username='%s' and password='%s';" % (uname, pwd)

    # 预编译思想, 用%s来占位, 在之后执行SQL语句时, 传入具体的值即可.
    sql = "select * from users where username=%s and password=%s;"

    # 细节: 定义容器变量, 记录: 账号和密码.
    params = (uname, pwd)
    # 4. 执行SQL语句, 获取结果集, 判断是否登录成功.
    cursor.execute(sql, params)     # 执行SQL语句时, 传入SQL语句, 及给占位符填充的参数.
    result = cursor.fetchone()
    if result:
        print('登录成功!')
    else:
        print('登陆失败!')
finally:
    # 5. 关闭游标和数据库连接, 释放资源.
    cursor.close()
    conn.close()

坚持分享 共同进步 如有错误 欢迎指出

相关推荐
梅雅达编程笔记4 分钟前
一份 PDF 到底该拆成什么存进去:RAG 智能问答毕设数据库设计完整教程
python·flask·智能问答·毕设·向量数据库·rag·数据库设计
loopfde成序19 分钟前
Node.js + SQLite 多租户交付台账工程实践:WAL 并发治理、VACUUM INTO 快照与乐观锁防覆盖
数据库·sqlite·node.js
AI创界者20 分钟前
Python 进阶实战(第八十三章):基于 Redis Lua 脚本的分布式令牌桶限流、异步熔断器状态机与信号优雅关机实战
人工智能·python·aigc
ZhengEnCi23 分钟前
所有账号存一张表,权限怎么做隔离:从RBAC表结构到行级隔离的落地写法
数据库·后端·postgresql
敲上瘾8 小时前
Qt 主窗口QMainWindow:菜单栏、工具栏、状态栏与浮动窗口等
开发语言·c++·qt·ui·qt6.3
富贵儿9989 小时前
NL2SQL 实践手记 05:表结构之外,还有业务知识——给查询流程接上 RAG
数据库·sql·ai·自然语言处理·langchain
csdn_aspnet10 小时前
如何使用 Docker 设置 PostgreSQL
运维·数据库·docker·postgresql·容器
Thanks_ks11 小时前
提示词工程实战:用结构化提示词让大模型输出稳定可控
python·大模型·json·openai·提示词工程·deepseek·系统提示词
倔强的石头_12 小时前
KES Studio 与 DMS 辅助开发管理实践:让接入过程可视化
数据库
BK贝壳13 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy