不能在SQL中动态绑定对象名,只能绑定值。对于这种行为,您必须使用字符串操作:
queryTemplate = 'SELECT * FROM %s'
tableName = 'Students'
query = queryTemplate % tableName
print(query)
为了解决评论中的问题——是的,这种技术确实更容易受到SQL注入攻击。在这种情况下,防止SQL注入的常见做法是使用允许表的白名单。
allowedTables = ['students', 'teachers']
if tableName not in allowedTables:
raise ValueError('Wrong table')