我有一个脚本可以从天气API&将此信息保存到localhost上的MySQL数据库中。我想让UPDATE脚本阻止任何SQL注入,但以下似乎根本不运行UPDATE。当我检查数据库时,似乎没有执行查询。
有人可以提出这个问题吗?我正在使用mysql.connector import / plugin
def save_to_database(self, uid):
sql = "UPDATE weather_data " \
"SET temperature=%s, temperature_feels=%s, humidity=%s, precipitation=%s, weather_status=%s " \
"WHERE UID =%s"
temperature = self.weather_data['temperature']
temperature_feels = self.weather_data['temperature_feels']
humidity = self.weather_data['humidity']
precipitation = self.weather_data['precipitation']
weather_status = self.weather_data['type']
print(sql)
c = self._db.cursor()
c.execute(sql, (temperature, temperature_feels, humidity, precipitation, weather_status, uid))
以下工作正常 - 但不是'安全'
def save_weather_forecast(self, uid):
print(self.weather_data);
sql = "UPDATE weather_data SET temperature = "+ str(self.weather_data['temperature']) + ", " \
+"temperature_feels = "+ str(self.weather_data['temperature_feels']) +", " \
+"humidity = "+ str(self.weather_data['humidity']) +", " \
+"weather_status = '"+ str(self.weather_data['type']) +"', " \
+"precipitation = "+ str(self.weather_data['precipitation']) +"" \
+" WHERE UID = '"+ str(uid) +"'"
print(sql)
c = self._db.cursor()
c.execute(sql)
c.close()
答案 0 :(得分:1)
Python DB API标准explicitly turns off auto commit,这意味着您必须手动提交任何事务,否则它们不会在数据库中生效。
提交是在连接时完成的,因此您需要添加:
self._db.commit()
c.execute()
行之后。