保存到数据库以防止Python中的SQL注入



我有一个从天气API&将这些信息保存到localhost上的MySQL数据库中。我想让UPDATE脚本阻止任何SQL注入,但下面的脚本似乎根本没有运行UPDATE。没有错误,只是当我检查数据库时,查询似乎没有执行。

有人能提出这个问题吗?我使用的是mysql.connector导入/插件

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()

Python DB API标准显式关闭自动提交,这意味着您必须手动提交任何事务,否则它们不会在数据库中受到影响。

提交是在连接时完成的,因此您需要添加:

self._db.commit()

在CCD_ 1行之后。

最新更新