保存到数据库以防止 SQL 在 Python 中注入
Saving to database to prevent SQL injection in Python
我有一个脚本可以从天气 API 中提取数据并将此信息保存到本地主机上的 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))
更新
以下工作正常 - 但不是 'safe'
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 标准 explicitly turns off auto commit 这意味着您必须手动提交任何事务,否则它们不会在数据库中生效。
提交是在连接时完成的,因此您需要添加:
self._db.commit()
在 c.execute()
行之后。
我有一个脚本可以从天气 API 中提取数据并将此信息保存到本地主机上的 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))
更新
以下工作正常 - 但不是 'safe'
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 标准 explicitly turns off auto commit 这意味着您必须手动提交任何事务,否则它们不会在数据库中生效。
提交是在连接时完成的,因此您需要添加:
self._db.commit()
在 c.execute()
行之后。