def login_change(self): print(str(self.admin_username.get())) print(str(self.admin_pass.get())) admin_pass = None # 数据库操作 查询管理员表 db = pymysql.connect(host='localhost', port=3306, db='crime', user='qingying', password='123456' ) sql = "SELECT * FROM admin_id WHERE admin_id = '%s'" % (self.admin_username.get()) # SQL 查询语句 try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: admin_id = row[0] admin_pass = row[1] # 打印结果 print("admin_id=%s,admin_pass=%s" % (admin_id, admin_pass)) except: print("Error: unable to fecth data") messagebox.showinfo('警告!', '用户名或密码不正确!') db.close() # 关闭数据库连接 print("正在登陆管理员修改密码界面") print("self", self.admin_pass) print("local", admin_pass) if self.admin_pass.get() == admin_pass: AdminChange(self.window) else: messagebox.showinfo('警告!', '用户名或密码不正确!')
时间: 2024-02-14 09:11:30 浏览: 62
这段代码中还有一个潜在的问题是 SQL 注入攻击。因为在 SQL 语句中使用了字符串格式化,而字符串格式化不能防止 SQL 注入攻击。应该使用参数化查询语句来避免这个问题。
修改后的代码如下:
```
def login_change(self):
print(str(self.admin_username.get()))
print(str(self.admin_pass.get()))
admin_pass = None
# 数据库操作 查询管理员表
db = pymysql.connect(host='localhost', port=3306, db='crime', user='qingying', password='123456')
sql = "SELECT * FROM admin_id WHERE admin_id = %s" # 参数化查询语句
try:
with db.cursor() as cursor:
# 执行SQL语句
cursor.execute(sql, (self.admin_username.get(),))
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
admin_id = row[0]
admin_pass = row[1]
# 打印结果
print("admin_id=%s,admin_pass=%s" % (admin_id, admin_pass))
except:
print("Error: unable to fecth data")
messagebox.showinfo('警告!', '用户名或密码不正确!')
finally:
db.close() # 关闭数据库连接
print("正在登陆管理员修改密码界面")
print("self", self.admin_pass)
print("local", admin_pass)
if self.admin_pass.get() == admin_pass:
AdminChange(self.window)
else:
messagebox.showinfo('警告!', '用户名或密码不正确!')
```
修改后的代码使用参数化查询语句,将用户名作为参数传入 `execute()` 方法中,避免了 SQL 注入攻击。此外,使用了 `with` 语句来创建游标,避免了手动关闭游标的问题。
阅读全文