我注意到大多数消息来源都说在 Python 中执行 SQL 语句的最佳实践是这样的:
cursor.execute( 'select * from coworkers where name = :1 and clue > :2', [ name, clue_threshold ] )
其他消息称
cursor.execute( "select * from coworkers where name = %s and clue > %s", ( name, clue_threshold ) )
我认为这很相似。
无论如何,我一直在做的是创建字典和存储值。比如初始字典biz_info
看起来像这样:
biz_info = {
'business' : None,
'name' : None,
'neighborhood' : None,
'address' : None,
'city' : None,
'state' : None,
'zip_code' : None,
'latitude' : None,
'longitude' : None,
'phone' : None,
'url' : None,
'yelp_url' : None,
}
然后我像这样执行SQL语句
execute_sql( cur, "insert into " + TABLE_BIZ_NAME + """ values (
NULL,
%(name)s,
%(neighborhood)s,
%(address)s,
%(city)s,
%(state)s,
%(zip_code)s,
%(latitude)s,
%(longitude)s,
%(phone)s,
%(url)s,
%(yelp_url)s,
NULL
)"""
, biz_info )
这对 sql 注入(inject)安全吗?我想用字典来存储信息,因为它更容易管理。
老实说,我什至不完全确定使用 %
有什么区别? , ,
, %s
, %d
, 和 %()s
表示在参数化查询中。基本上我所知道的就是不使用
cursor.execute( "select * from coworkers where name = '%s' and clue > %d" % ( name, clue_threshold ) )
最佳答案
用于将参数传递给 sql 命令字符串的方式取决于数据库(例如,sqlite 使用 ?
)。
根据 MySQLdb documentation ,您可以使用 paramstyle
参数来设置格式化字符串的首选方式(format
或 pyformat
)。
您问题中的第一个示例似乎不受支持。无论如何,我要说的是,只要您不像上一个示例那样格式化整个字符串,您就是安全的,因为可以假设查询参数将被正确转义。
关于python - 使用 MySQLdb 在 Python 中执行这样的 SQL 查询是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184721/