• pymysql模块


    一、链接

    import pymysql
    user=input('用户名: ').strip()
    pwd=input('密码: ').strip()

    #链接
    conn=pymysql.connect(host='localhost',user='root',password='123',database='egon',charset='utf8')

    二、执行(默认返回元组形式)

    # 光标
    cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示
    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)返回字典

    三、执行sql语句

    sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) #注意%s需要加引号
    print(sql)
    res=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目
    print(res)

    # 退出/断开链接
    cursor.close()
    conn.close()

    if res:
        print('登录成功')
    else:
        print('登录失败')

    四、execute(注入问题)

    PS:sql语句中的--符号以及#都是注释符号

    就根据程序的字符串拼接name='%s' ,当输入是xxx--hhh形式时,sql语句就会判断条件name=xxx--hhh

    两种情况

    #1、sql注入之:用户存在,绕过密码
    egon' -- 任意字符

    #2、sql注入之:用户不存在,绕过用户与密码
    xxx' or 1=1 -- 任意字符

    1588953322894

    解决方法:

    原来我们自己拼接字符串——改成execute帮我们做拼接

    sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上
    res=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。

    五、增删改查

    # 1.针对增删改 pymysql需要二次确认才能真正的操作数据
    import pymysql

    # 链接
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        passwd = '123456',
        db = 'day48',
        charset = 'utf8',
        autocommit = True
    )
    # 光标
    cursor = conn.cursor(pymysql.cursors.DictCursor) # 返回字典

    # 增
    sql = 'insert into user(name,password) values(%s,%s)'
    rows = cursor.executemany(sql,[('xxx',123),('ooo',123),('yyy',123)])
    # 确认
    conn.commit()

    # 改
    sql = 'updata user set name = "jasonNB" where id = 1'
    rows = cursor.execute(sql)
    conn.commit()

    # 删
    sql = 'delete from user where id =7'
    rows = cursor.execute(sql)
    conn.commit()

    # 查
    sql = 'select * from user'
    cursor.execute(sql)
    print(cursor.fetchall())

    ps:增删改都需要二次确认

  • 相关阅读:
    A1020 Tree Traversals [中序后序建树]
    bfs 找步数最少的迷宫路径
    hdu 1241
    hdu 素数环
    A1054 The Dominant Color [map]
    A1097 Deduplication on a Linked List [链表去重]
    C# 中Dictionary的用法及用途
    C#文件操作
    C# 属性概述
    C# Lock的用法
  • 原文地址:https://www.cnblogs.com/bailongcaptain/p/12858860.html
Copyright © 2020-2023  润新知