python cx_Oracle无效标识符

时间:2019-02-18 12:58:17

标签: python oracle python-2.7 cx-oracle

我正在尝试查询oracle数据库。

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

2 个答案:

答案 0 :(得分: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注入攻击。

答案 1 :(得分:0)

  

public class UrlActivity extends AppCompatActivity { private Advertisement adv; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_url); viewPager = (ViewPager)findViewById(R.id.viewPager); //adv is a custom object that contain an arraylist<String> of url. adv = (Advertisement)getIntent().getSerializableExtra("adv"); ViewPagerAdapterUrl viewPagerAdapterUrl = new ViewPagerAdapterUrl(this, adv.getPhotosUrl()); viewPager.setAdapter(viewPagerAdapterUrl); }

在SQL中,双引号用于数据库标识符名称(表和列),而不是字符串文字。因此,Oracle编译器正在寻找名为cur.execute('select * from admin.summary where NUMBER = "C123456"'的列。

  

C123456

您的字符串用单引号引起来,因此它在cur.execute('select * from admin.summary where NUMBER = 'C1012445'')之后结束,Python解释器不知道如何处理=

尝试像这样转义引号:

C123456

正如@ChristopherJones指出的那样,cur.execute('select * from admin.summary where NUMBER = ''C1012445'' ') 是保留字,不能在Oracle中用作名称。我以为所发布的代码是一个修订,但是如果有人愚蠢到无法强制使用这样的列名,那么他们必须使用双引号来实现。在这种情况下,该列的所有后续引用也必须用双引号转义:

NUMBER