我在 Python 中使用 cx_Oracle,但无法获取用作表名的变量,如这个简单的示例所示:
query = "select * from some.:usertable.userinfo"
bindvars = {'usertable':usertable}
cursor.execute(query, bindvars)
正确的语法是什么?当我使用 WHERE
... 等但不使用表名时,变量替换工作正常。我想我必须以某种方式分离“:usertable”......
最佳答案
数据库适配器很少支持对任何非“值”(需要引用的内容)使用参数。要么使用字符串格式(狡猾,你会面临 SQL 注入(inject)的风险),要么使用 SQLAlchemy 之类的库,它可以让你使用 Python 代码生成有效的 SQL。
如果您确定您的 usertable
值是正常的(例如,根据现有表名称列表进行检查),则以下操作可行:
query = 'select * from some.{usertable}.userinfo'.format(usertable=usertable)
关于python - 使用 cx_Oracle 将变量绑定(bind)到表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124572/