python cx_Oracle无效标识符

问题描述 投票:0回答:2

我正在尝试查询oracle db。

import cx_Oracle

dsn_tns = '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=some.server.com)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service_name)))'
con = cx_Oracle.connect('USER', 'PWD', dsn_tns)

cur = con.cursor()
cur.execute('select * from admin.summary where NUMBER = "C123456"')

res = cur.fetchall()
print res

cur.close()
con.close()

得到了:

$ python cx_oracle.py
Traceback (most recent call last):
  File "cx_oracle.py", line 9, in <module>
    cur.execute('select * from admin.summary where NUMBER = "C123456"')
cx_Oracle.DatabaseError: ORA-00936: missing expression

我还尝试将查询字符串更改为

'select * from admin.summary where NUMBER = 'C1012445''

得到了:

$ python cx_oracle.py
  File "cx_oracle.py", line 9
    cur.execute('select * from admin.summary where NUMBER = 'C1012445'')
                                                                    ^
SyntaxError: invalid syntax

有什么建议吗? Python版本是2.7

python oracle python-2.7 cx-oracle
2个回答
1
投票

NUMBER是SQL中用于数据类型的保留字。默认情况下,它不是列名,除非有人强制它:

SQL> create table t ("NUMBER" number);

Table created.

如果他们这样做,那么你的SQL需要引用列名,如:

cur.execute("""select "NUMBER" from t where "NUMBER" = 1""")

或者,在您的情况下,如:

cur.execute("""select * from admin.summary where "NUMBER" = 'C123456'""")

但是,除非您始终在'where'子句中使用相同的值,否则应使用C123456的绑定变量。看看https://github.com/oracle/python-cx_Oracle/blob/master/samples/BindQuery.py是怎么做到的。

使用绑定变量有助于扩展,并有助于阻止SQL注入攻击。


0
投票

cur.execute('select * from admin.summary where NUMBER = "C123456"'

在SQL中,双引号用于数据库标识符名称(表和列),而不是字符串文字。因此Oracle编译器正在寻找一个名为C123456的列。

cur.execute('select * from admin.summary where NUMBER = 'C1012445'')

你的字符串以单引号为界,所以它在=之后结束,Python解释器不知道如何处理C123456

尝试转义这样的引号:

cur.execute('select * from admin.summary where NUMBER = ''C1012445'' ')

正如@ChristopherJones所指出的那样,NUMBER是一个保留字,不能在Oracle中用作名称。我假设发布的代码是一个编辑,但如果有人愚蠢到强制通过这样的列名,他们必须通过使用双引号来完成。在这种情况下,对列的所有后续引用也必须通过双引号进行转义:

cur.execute('select * from admin.summary where "NUMBER" = ''C1012445'' ')
© www.soinside.com 2019 - 2024. All rights reserved.