python - 使用 MySQLdb 在 Python 中执行这样的 SQL 查询是否安全?

标签 python mysql mysql-python

我注意到大多数消息来源都说在 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 参数来设置格式化字符串的首选方式(formatpyformat)。

您问题中的第一个示例似乎不受支持。无论如何,我要说的是,只要您不像上一个示例那样格式化整个字符串,您就是安全的,因为可以假设查询参数将被正确转义。

关于python - 使用 MySQLdb 在 Python 中执行这样的 SQL 查询是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184721/

相关文章:

python - 如何保护 python 中的 mysqldb 连接?

python - 我如何解释测试数据上的性能下降?

Python:组合来自 4 个列表的元素并跳过其中有重复项的列表组合

python - 多项选择 react python (discord.py)

python - 将数据帧转换为 numpy 矩阵

c# - 如何显示来自两个不同表的日期?

python - mysqldb 中的转义值

python - 为什么现在还有 "commands out of sync; you can' t run this command”错误

mysql - AWS : Not able to connect to mysql(rds) from wordpress

php mysql 搜索今天日期的开始和结束日期字段(如果它落在范围内)