场景说明
用python操作mysql时,经常会遇到写的sql语句中带有in,同时还要给in中传递参数,直接使用%s
来替换会存在sql注入的风险,遂多方查找,得到以下方法,供大家使用
具体代码
import pymysql
conn = pymysql.connect(
host='127.0.0.1', # 连接名称,默认127.0.0.1
user='root', # 用户名
passwd='123456', # 密码
port=3306, # 端口,默认为3306
db='mydb', # 数据库名称
charset='utf8', # 字符编码
)
cs = conn.cursor()
img_ids = [1,2,3] # 需要传入sql的数据
sql = "select img_url from img_url_table where id in %s"
cs.execute(sql, (img_ids, )) # 直接传递元组包裹列表即可,注意是元组,逗号不能丢