我要的是执行sql
从作者喜欢“%steven%”的文章中选择 *
。
为了安全起见,我是这样使用的:
cursor.execute('select * from articles where %s like %s', ('author', '%steven%')
那么结果就是空的,不是语法错误,而是空集。 但我很确定里面有东西,我可以使用第一个 sql 得到结果。我的代码有什么运行吗?
最佳答案
您不能在where %s like %s
处将列名称设置为参数。要动态设置列名,您需要进行实际的字符串操作,例如:
sql = 'select * from articles where '+ sql_identifier('author') +' like %s'
cursor.execute(sql, ('%steven%',))
其中 sql_identifier
是您的库的函数,用于使标识符对 SQL 注入(inject)安全。像这样的东西:
# don't actually use this!
def sql_identifier(s):
return '"%s"' % s.replace('"','')
但是通过实际测试并了解您正在使用的数据库引擎。
关于python - 无法在 pymysql 中正确格式化 sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44937003/