python - 使用 cx_Oracle 将变量绑定(bind)到表名

标签 python oracle cx-oracle

我在 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/

相关文章:

python - 如何正常中断urllib2下载?

Python eval 表示包含网络路径(反斜杠)、奇怪行为或预期的字典的字符串?

python 2 : calculate using user defined/named variables

Windows Function App 不支持 Python 项目。部署到 Linux 函数应用程序

oracle - perl中如何处理模块抛出的错误

python-2.7 - 如何获取 Python 字典值列表并在 Kivy UI 中显示为表格(使用 ListView 小部件)?

python - 在 Windows 上轻松安装 cx_Oracle(python 包)

python - 在cx_oracle python中获取序列号

sql - 求和年、月、日 - Oracle SQL

oracle - 自动设置Oracle的序列起始值