往mysql中插入 字符串数据时 包含一些特殊字符时的处理,防止sql注入

比如:address字符串中 包含 \  '  " 时候 在拼接sql语句时,必须在这些字符前加上转义字符 \ 才可以不影响sql语句,可以用字符串处理函数将对应的字符替换成带有转义的字符即可
address = address.replace("\\","\\\\")
address = address.replace("'","\\'")
address = address.replace('"','\\"')

特殊的字符可能会引起sql的注入,我们应该尽量使用mysql提供的接口去传参,而不是 自己去拼接sql语句
例如:mysql官方手册api 就解释的很清处
https://dev.mysql.com/doc/connector-python/en/connector-python-reference.html
比如已python为例:

# 插入单条数据
insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

# 字典方式
select_stmt = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
cursor.execute(select_stmt, { 'emp_no': 2 })
data = [
  ('Jane', date(2005, 2, 12)),
  ('Joe', date(2006, 5, 23)),
  ('John', date(2010, 10, 3)),
]
# 插入多条数据
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)

# 实际是这样的结果
#INSERT INTO employees (first_name, hire_date)
#VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')

你可能感兴趣的:(MySQL)