• pymysql 操作 , sql注入


    1,安装:

    pip3 install pymysql
    
    import pymysql
    
    注意:
        a.文件名不能写自己本身
        b.connect ----> conn ----> cursor
        c.执行sql语句  ---> execute(sql)
        d.取数据:
            fetchone()
            fetchall()
            fetchamany(size)
        e.增加删除:
            conn.commit()

    2,链接:

    import  pymysql
    
    # 连接mysql服务器
    conn = pymysql.connect(host='localhost', user='root', password='123',database='db2', charset='utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    sql = "select * from student where id > %s " % (12,)
    
    cursor.execute(sql)
    
    # res = cursor.fetchone()
    res = cursor.fetchmany(10)
    # res = cursor.fetchall()  ### 列表里面套字典
    print(res)
    
    cursor.close()
    conn.close()

    3,操作:

    import  pymysql
    
    # 连接mysql服务器
    
    conn = pymysql.connect(host='localhost', user='root', password='123',database='db1', charset='utf8')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    sql = "delete from t7 where id=3"
    cursor.execute(sql)
    
    ###  删除和更新的时候, 需要事物提交
    conn.commit()
    
    
    # res = cursor.fetchone()
    # res = cursor.fetchmany(10)
    # res = cursor.fetchall()  ### 列表里面套字典
    # print(res)
    
    cursor.close()
    conn.close()
    注意:
                
        a. conn, cursor 用完了需要关闭资源连接
                
        b. 查询的时候, fetchone, fetchmany, fetchall,  默认返回的是元组, 需要返回字典的话: cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
                
        c. 删除和更新的时候, 需要在execute之后, 添加 conn.commit()

    4,sql注入

    a. 登录验证
        
        写sql语句的时候, %传值的时候, 需要加引号:
            sql = "select * from t4 where name = '%s' and pwd = '%s'" % (username, pwd)
        
        上面的sql语句带来的风险是:
        
            例一:
                username = zekai' #
                
                select * from t4 where name = 'zekai' #' and pwd = ''
            
            例二:
                username = dbsahvbdsha' or 1=1 #
                
                select * from t4 where name = 'dbsahvbdsha' or 1=1 
    上面出现的问题,我们称之为 SQL注入 (
    **********************************) 出现问题的根源是: 因为太过于相信用户的输入, 导致我们在接受用户输入的参数的时候, 并没有对他进行转义 解决SQL注入: 1. 自己手工对用户输入的值进行转义 2. 使用execute()自动进行过滤 sql = "select * from t4 where name = %s and pwd = %s" cursor.execute(sql,(username, pwd)) #$## 插入一条 cursor.execute(sql, ('lxxx', '1234'))
    ### 插入多条 data = [ ('aaaaa', 'aaa'), ('bbbb', 'bbb'), ('ffff', '666'), ('rrrr', '888'), ] cursor.executemany(sql, data) try: cursor.execute(sql, ('lxxx', '1234')) ### 删除和更新的时候, 需要事物提交 conn.commit() except Exception as e: conn.rollback() cursor.lastrowid : 最后一行的行数
  • 相关阅读:
    区块链共识算法整理
    用Python实现GBDT算法并处理Iris数据集
    用Python实现岭回归算法与Lasso回归算法并处理Iris数据集
    软件体系结构结课报告
    用Python实现支持向量机并处理Iris数据集
    HTML标签(三)
    HTML标签(二)
    HTML标签(一)
    HTML简介
    开始。
  • 原文地址:https://www.cnblogs.com/HZLS/p/11045939.html
Copyright © 2020-2023  润新知