防止 sql 注入 mysqldb python3.6
Preventing sql injections mysqldb python3.6
这是我使用 MySQLdb 和 python3.6
的脚本
import MySQLdb
# start connection
db = MySQLdb.connect("localhost", "root", "asdf", "projecten")
# create cursor
c = db.cursor()
# insert multiple records using a tuple
cities = [
('Boston', 'MA', 600000),
('Chicago', 'IL', 2700000),
('Houston', 'TX', 2100000),
('Phoenix', 'AZ', 1500000)
]
# sql statement
sql = "INSERT INTO projecten.population(city, state, population) VALUES(%s, %s, %s)"
# insert data into table with list cities
c.executemany(sql, cities)
# commit changes
db.commit()
# close connection
db.close()
这对 sql 注射安全吗,因为有些人使用 ?而不是 %s 但在 python3.6 上不起作用
作为 Bruno says in an answer 相关问题:
To avoid injections, use execute
with %s
in place of each variable, then pass the value via a list or tuple as the second parameter of execute
.
按照此建议,您可以像这样创建 SQL:
sql ="""INSERT INTO projecten.population (city, state, population)
VALUES (%s, %s, %s)"""
c.executemany(sql, cities)
这是一种比您现在使用的方法更安全的方法。
这是我使用 MySQLdb 和 python3.6
的脚本import MySQLdb
# start connection
db = MySQLdb.connect("localhost", "root", "asdf", "projecten")
# create cursor
c = db.cursor()
# insert multiple records using a tuple
cities = [
('Boston', 'MA', 600000),
('Chicago', 'IL', 2700000),
('Houston', 'TX', 2100000),
('Phoenix', 'AZ', 1500000)
]
# sql statement
sql = "INSERT INTO projecten.population(city, state, population) VALUES(%s, %s, %s)"
# insert data into table with list cities
c.executemany(sql, cities)
# commit changes
db.commit()
# close connection
db.close()
这对 sql 注射安全吗,因为有些人使用 ?而不是 %s 但在 python3.6 上不起作用
作为 Bruno says in an answer 相关问题:
To avoid injections, use
execute
with%s
in place of each variable, then pass the value via a list or tuple as the second parameter ofexecute
.
按照此建议,您可以像这样创建 SQL:
sql ="""INSERT INTO projecten.population (city, state, population)
VALUES (%s, %s, %s)"""
c.executemany(sql, cities)
这是一种比您现在使用的方法更安全的方法。