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()

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

相关推荐
AAA小肥杨23 分钟前
基于k8s的Python的分布式深度学习训练平台搭建简单实践
人工智能·分布式·python·ai·kubernetes·gpu
LXS_35728 分钟前
Day 05 C++ 入门 之 指针
开发语言·c++·笔记·学习方法·改行学it
etsuyou2 小时前
js前端this指向规则
开发语言·前端·javascript
shizhenshide2 小时前
为什么有时候 reCAPTCHA 通过率偏低,常见原因有哪些
开发语言·php·验证码·captcha·recaptcha·ezcaptcha
lichong9512 小时前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
Tiny番茄2 小时前
31.下一个排列
数据结构·python·算法·leetcode
mit6.8242 小时前
[Agent可视化] 配置系统 | 实现AI模型切换 | 热重载机制 | fsnotify库(go)
开发语言·人工智能·golang
呼哧呼哧.2 小时前
Spring的核心思想与注解
数据库·sql·spring
友友马2 小时前
『 QT 』QT控件属性全解析 (一)
开发语言·前端·qt
小白学大数据3 小时前
实战:Python爬虫如何模拟登录与维持会话状态
开发语言·爬虫·python