【问题标题】:SQL statement executes in sql developer but fetches entire table in python (cx_Oracle)SQL 语句在 sql developer 中执行,但在 python (cx_Oracle) 中获取整个表
【发布时间】:2013-12-09 21:06:58
【问题描述】:

我正在尝试使用 cx_Oracle 从 Python 执行 sql 语句。我编写的 SQL 似乎可以在我的 Oracle 数据库客户端 (SQL Developer) 中工作,但在从 Python 脚本执行时似乎会拉回每条记录

#setup db connection here...
curs = db.cursor()

sql=("\
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
FIRST_DB.second_table b,\
OTHER_DB.third_table c\
\
WHERE\
a.identifier='XXXX' and\
a.this_row = b.that_row and\
b.this_row = c.that_row;\
")

curs.execute(sql)
print curs.description
result=curs.fetchmany()
while result:
    for i,j,k,l in result:
        print i,j,k,l
    result=curs.fetchmany()
db.close()

这会返回视图中的每条记录,而不仅仅是 SQL 开发人员中包含“XXXX”的记录...

任何人都可以看到 SQL 中的问题或我这样做的方式吗?

提前干杯

【问题讨论】:

    标签: python sql oracle oracle-sqldeveloper cx-oracle


    【解决方案1】:

    据我所知,SQL*Plus 等一些工具在 sql 语句中存在空行问题。不确定 Python 如何将您的语句传递给数据库,但也许在您的 where 子句之前删除该空行会有所帮助:

    #setup db connection here...
    curs = db.cursor()
    
    sql=("\
    SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
    FIRST_DB.second_table b,\
    OTHER_DB.third_table c\
    WHERE\
    a.identifier='XXXX' and\
    a.this_row = b.that_row and\
    b.this_row = c.that_row;\
    ")
    
    curs.execute(sql)
    print curs.description
    result=curs.fetchmany()
    while result:
        for i,j,k,l in result:
            print i,j,k,l
        result=curs.fetchmany()
    db.close()
    

    【讨论】:

      【解决方案2】:

      尝试使用triple-quoted strings。这是拥有可读的多行字符串的好方法。我没有要在这里测试的 Oracle DB,但我猜缺少空白会导致您出现问题。

      打印您的 SQL 语句,您将看到删除反斜杠后它的实际外观:

      sql=("\
      SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
      FIRST_DB.second_table b,\
      OTHER_DB.third_table c\
      \
      WHERE\
      a.identifier='XXXX' and\
      a.this_row = b.that_row and\
      b.this_row = c.that_row;\
      ")
      
      >>> print sql
      
      SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,FIRST_DB
      .second_table b,OTHER_DB.third_table cWHEREa.identifier='XXXX' anda.this_row = b
      .that_row andb.this_row = c.that_row;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-27
        • 1970-01-01
        • 2019-05-18
        • 2018-01-19
        • 2013-08-11
        相关资源
        最近更新 更多