2017-06-03 78 views
-1

我的要求如下。找到一个表(*)为一个表,如果不存在,创建一个。以下是显示问题的示例代码。在这两种情况下,其他条件即将到来。不知道我如何实现这一点,任何帮助表示赞赏。蟒蛇甲骨文如果其他问题的行取

import cx_Oracle 
import os 
import datetime 

ts = datetime.datetime.now() 
con = cx_Oracle.connect('xxxx/[email protected]:1521/xxxxx') 
print con.version 
cur = con.cursor() 
cur.execute('select count(*) from AAA.AAA_TEST') 
rows = cur.fetchall(); 
print rows 
print len(rows) 
if (rows ==1): 
    print 'there is a row' 
else: 
    print 'there is no row' 


#result 1 where the row exists 
11.2.0.4.0 
[(1,)] 
1 
there is no row 

Process finished with exit code 0 

#result 2 where the row do not exists 
11.2.0.4.0 
[(0,)] 
1 
there is no row 

Process finished with exit code 0 

回答

0

SELECT COUNT(*)总是返回一行 - 如果表中没有对象或者具有对象的数量,则返回0。所以总是有1行,你应该测试计数,而不是行数。所以使用if (rows[0][0] >= 1):

rows[0]返回第一行,rows[0][0]给出第一行的第一列;对于你的SELECT COUNT(*)第一列是计数,所以你测试,如果计数是0,如果它> = 1。

+0

对不起,没有帮助,如果你看到的代码中,我已经使用过,在这两种情况下显示1. – Shanker

+0

更改后的代码有帮助吗? – phd

+0

对不起,请等一分钟,我会更新你。它似乎以这种方式工作。让我做几个测试。提前致谢。 – Shanker