非安全的方式,使用动态拼接SQL
输入' or 1 = 1 or '1
sql ="""SELECT * FROM goods WHERE name = '%s';""" % find_name
from pymysql import connect
class JD(object):
def __init__(self):
# 创建connect连接
self.conn = connect(host='127.0.0.1', port=3306, user='root',
password='123456', database='jing_dong', charset='utf8')
# 获得cursor对象
self.cursor = self.conn.cursor()
def execute_sql(self, sql):
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
def get_info_by_name(self):
"""根据名字查询一个商品"""
find_name = input('请输入想要查询的商品名称: ')
sql = """SELECT * FROM goods where name = '%s'""" % find_name
# 打印拼接出的字符串
print('------>%s<------' % sql)
self.execute_sql(sql)
@staticmethod
def print_menu():
print('-----京东-----')
print('1.查询商品信息')
return input('请输入功能对应的序号: ')
def run(self):
while True:
op = self.print_menu()
if op == '1':
self.get_info_by_name()
else:
print('输入错误...')
def main():
jd = JD()
jd.run()
if __name__ == '__main__':
main()
SQL注入执行效果
因为使用动态拼接SQL,所以在应该输入的地方拼接了' or 1 = 1 or '1
,打印出来的SQL为SELECT * FROM goods where name = '' or 1=1 or'1'
,SQL恒真,相当于where条件失效,等价于SELECT * FROM goods
,导致整表的数据被查询出来。
安全的方式,构造参数列表
params = []
sql = 'SELECT * FROM goods where name = %s'
self.cursor.execute(sql, params)
from pymysql import connect
class JD(object):
def __init__(self):
# 创建connect连接
self.conn = connect(host='127.0.0.1', port=3306, user='root',
password='123456', database='jing_dong', charset='utf8')
# 获得cursor对象
self.cursor = self.conn.cursor()
def execute_sql(self, sql):
self.cursor.execute(sql)
for temp in self.cursor.fetchall():
print(temp)
def get_info_by_name(self):
"""根据名字查询一个商品"""
find_name = input('请输入想要查询的商品名称: ')
params = [find_name]
sql = 'SELECT * FROM goods where name = %s'
self.cursor.execute(sql, params)
print(self.cursor.fetchall())
print('------>%s<------' % sql)
@staticmethod
def print_menu():
print('-----京东-----')
print('1.查询商品信息')
return input('请输入功能对应的序号: ')
def run(self):
while True:
op = self.print_menu()
if op == '1':
self.get_info_by_name()
else:
print('输入错误...')
def main():
jd = JD()
jd.run()
if __name__ == '__main__':
main()
SQL注入执行效果
注意:如果要有多个参数,需要进行参数化。
params = [数值1, 数值2...]
,此时SQL语句要有多个%s