sql注入:
1 from pymysql import * 2 3 4 def main(): 5 # 创建连接 6 conn = connect(host="127.0.0.1", port=3306, database="python_1", user="root", password="mysql", charset="utf8") 7 # 创建cursor对象 8 cursor = conn.cursor() 9 find_name = input("请输入要查询的商品名称:") # ' or 1=1 or '1 10 # sql = "select * from test;" 11 sql = """select * from test where name='%s';""" % find_name; 12 # 打印sql语句 13 print("------->%s<------" % sql) # select * from test where name='' or 1=1 or '1'; 14 # 执行sql语句 15 cursor.execute(sql) 16 for temp in cursor.fetchall(): 17 print(temp) # (1, 'laoli') (2, 'zhangsan') (3, 'laowang') 18 # 关闭数据库 19 cursor.close() 20 conn.close() 21 22 23 if __name__ == '__main__': 24 main()
结果:
请输入要查询的商品名称:' or 1=1 or '1 ------->select * from test where name='' or 1=1 or '1';<------ (1, 'laoli') (2, 'zhangsan') (3, 'laowang')
防sql注入:
1 from pymysql import * 2 3 4 def main(): 5 # 创建连接 6 conn = connect(host="127.0.0.1", port=3306, database="python_1", user="root", password="root", charset="utf8") 7 # 创建cursor对象 8 cursor = conn.cursor() 9 find_name = input("请输入要查询的商品名称:") # ' or 1=1 or '1 10 sql = "select * from test where name=%s" 11 # 打印sql语句 12 print("------->%s<------" % sql) # select * from test where name=%s; 13 # 执行sql语句 把find_name放在中括号中传到execute()方法中去 14 cursor.execute(sql,(find_name,)) # excute(sql语句,元祖) 元祖里放参数 15 for temp in cursor.fetchall(): 16 print(temp) # 17 # 关闭数据库 18 cursor.close() 19 conn.close() 20 21 22 if __name__ == '__main__': 23 main()
结果:
请输入要查询的商品名称:' or 1=1 or '1 ------->select * from test where name=%s<------ 进程已结束,退出代码0