cx_Oracle: ORA-01036: 非法变量 name/number
cxOracle: ORA-01036: illegal variable name/number
我的代码中的简单变量绑定有问题:
conn_str = (f"oracle+cx_oracle://{self.params.user}:{urllib.parse.quote_plus(self.params.password)}"
f"@{self.params.host}:{self.params.port}/?service_name={self.params.service}")
self.engine = create_engine(conn_str)
with self.engine.connect() as conn:
s = text("""TRUNCATE TABLE :t1""")
conn.execute(s, t1=table_name)
错误:
sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-01036: illegal variable name/number
[SQL: TRUNCATE TABLE :t1]
[parameters: {'t1': 'hss_prod'}]
(Background on this error at: https://sqlalche.me/e/14/4xp6)
我查看了文档:
和类似的问题:
- https://github.com/oracle/python-cx_Oracle/issues/433
- DatabaseError: ORA-01036: illegal variable name/number
我无法理解它。
Oracle 不允许在 DDL 语句中绑定变量。这在有关绑定的链接 cx_Oracle 文档中提到,内容如下:
Bind variables also cannot be used in Data Definition Language (DDL)
statements, such as CREATE TABLE or ALTER statements.
是的,截断 table 语句是 DDL 语句!所以你唯一的选择是做这样的事情:
sql = f"truncate table {table_name}"
cursor.execute(sql)
如果 table_name
的值来自未知来源,请确保对其进行验证以避免 SQL 注入!
我的代码中的简单变量绑定有问题:
conn_str = (f"oracle+cx_oracle://{self.params.user}:{urllib.parse.quote_plus(self.params.password)}"
f"@{self.params.host}:{self.params.port}/?service_name={self.params.service}")
self.engine = create_engine(conn_str)
with self.engine.connect() as conn:
s = text("""TRUNCATE TABLE :t1""")
conn.execute(s, t1=table_name)
错误:
sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-01036: illegal variable name/number
[SQL: TRUNCATE TABLE :t1]
[parameters: {'t1': 'hss_prod'}]
(Background on this error at: https://sqlalche.me/e/14/4xp6)
我查看了文档:
和类似的问题:
- https://github.com/oracle/python-cx_Oracle/issues/433
- DatabaseError: ORA-01036: illegal variable name/number
我无法理解它。
Oracle 不允许在 DDL 语句中绑定变量。这在有关绑定的链接 cx_Oracle 文档中提到,内容如下:
Bind variables also cannot be used in Data Definition Language (DDL)
statements, such as CREATE TABLE or ALTER statements.
是的,截断 table 语句是 DDL 语句!所以你唯一的选择是做这样的事情:
sql = f"truncate table {table_name}"
cursor.execute(sql)
如果 table_name
的值来自未知来源,请确保对其进行验证以避免 SQL 注入!