python3参数化列表防止SQL注入

版权声明:本文由monkey原创撰写,转载请注明文章来源! https://blog.csdn.net/weixin_44143222/article/details/86669102

什么是SQL注入

产生原因: 后台将用户提交的带有恶意的数据和SQL进行字符串方式的拼接,从而影响了SQL语句的语义,最终产生数据泄露的现象。 如果防止: sql语句的参数化, 将SQL语句的所有数据参数存在一个列表中传递给execute函数的第二个参数

注意

  • 此处不同于python的字符串格式化,必须全部使用%s占位
  • 所有参数所需占位符外不需要加引号
from pymysql import connect


class JD(object):
    def __init__(self):
        # 创建和数据库服务器的连接 服务器地址、端口、户名、密码、数据库名、通信使用字符和数据库字符集一致
        conn = connect(host='localhost', port=3306, user='root', password='mysql', database='jing_dong', charset='utf8')
        # 获取游标
        self.cursor = conn.cursor()

    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def excute_sql(self,sql):
        self.cursor.execute(sql)
        for temp in  self.cursor.fetchall():
            print(temp)
	# # 非安全的方式
    # # 输入 " or 1=1 or "   (双引号也要输入)
    # sql = 'select * from goods where name="%s"' % find_name
    # print("""sql===>%s<====""" % sql)
    # # 执行select语句,并返回受影响的行数:查询所有数据
    # count = cs1.execute(sql)

	# 安全的方式
    # 构造参数列表 
    # 执行select语句,并返回受影响的行数:查询所有数据
    # args = "goods"
    # sql = "select * from %s;"%(args,)
    # 注意:
    # 如果要是有多个参数,需要进行参数化
    # 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可 
    def show_all_items(self):
        args = "goods"
        sql = "select * from %s;"%(args,)
        self.excute_sql(sql)

    def show_cates(self):
        args = "goods"
        sql = "select cate_name from %s;"%(args,)
        self.excute_sql(sql)

    def show_price(self):
        args = "goods"
        sql = "select price from %s;"%(args,)
        self.excute_sql(sql)

    def print_menu(self):
        print("-----京东-----")
        print("1:查询所有的商品的信息")
        print("2.查询所有商品的分类信息")
        print("3.查询所有商品的价格")
        print("4.添加商品种类")
        print("5.根据ID查询商品信息")
        print("6.根据ID查询商品信息安全方式")
        return input("请输入功能对应的序号:")

    def run(self):
        # 循环一个查询菜单
        while True:
            num = self.print_menu()
            if num == "1":
                # 查询所有的商品的信息
                self.show_all_items()
            elif num == "2":
                # 查询所有商品的分类信息
                self.show_cates()
            elif num == "3":
                # 查询所有商品的价格
                self.show_price()
            if num == "4":
                # 添加商品种类
                pass
            elif num == "5":
                # 根据ID查询商品信息
                pass
            elif num == "6":
                # 根据ID查询商品信息安全方式
                pass
            else:
                print("输入有误,请重新输入。。。")


def main():
    # 创建一个京东商城的对象
    jd = JD()
    # 调用这个对象的run方法,让其运行
    jd.run()


if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/weixin_44143222/article/details/86669102
今日推荐