2017-06-03 80 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