sql注入和防sql注入

时间:2022-01-19 13:00:08

sql注入:

 from pymysql import *

 def main():
# 创建连接
conn = connect(host="127.0.0.1", port=3306, database="python_1", user="root", password="mysql", charset="utf8")
# 创建cursor对象
cursor = conn.cursor()
find_name = input("请输入要查询的商品名称:") # ' or 1=1 or '1
# sql = "select * from test;"
sql = """select * from test where name='%s';""" % find_name;
# 打印sql语句
print("------->%s<------" % sql) # select * from test where name='' or 1=1 or '1';
# 执行sql语句
cursor.execute(sql)
for temp in cursor.fetchall():
print(temp) # (1, 'laoli') (2, 'zhangsan') (3, 'laowang')
# 关闭数据库
cursor.close()
conn.close() if __name__ == '__main__':
main()

结果:

请输入要查询的商品名称:' or 1=1 or '1
------->select * from test where name='' or 1=1 or '1';<------
(1, 'laoli')
(2, 'zhangsan')
(3, 'laowang')

  

防sql注入:

 from pymysql import *

 def main():
# 创建连接
conn = connect(host="127.0.0.1", port=3306, database="python_1", user="root", password="root", charset="utf8")
# 创建cursor对象
cursor = conn.cursor()
find_name = input("请输入要查询的商品名称:") # ' or 1=1 or '1
sql = "select * from test where name=%s"
# 打印sql语句
print("------->%s<------" % sql) # select * from test where name=%s;
# 执行sql语句 把find_name放在中括号中传到execute()方法中去
cursor.execute(sql,(find_name,)) # excute(sql语句,元祖) 元祖里放参数
for temp in cursor.fetchall():
print(temp) #
# 关闭数据库
cursor.close()
conn.close() if __name__ == '__main__':
main()

结果:

请输入要查询的商品名称:' or 1=1 or '1
------->select * from test where name=%s<------ 进程已结束,退出代码0