python oracle if else 问题获​​取行

python oracle if else issues for rows fetch

我的要求如下。查找 table 的计数 (*),如果不存在,则创建 one.following 是显示问题的示例代码。在这两种情况下,else 条件都来了。不知道我是如何做到这一点的,任何帮助表示赞赏。

import cx_Oracle
import os
import datetime

ts = datetime.datetime.now()
con = cx_Oracle.connect('xxxx/xxxx@xxxxx: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

SELECT COUNT(*) 总是 returns 一行 — 如果 table 中没有对象则为 0,或者为对象数。所以总是有 1 行,你应该测试计数,而不是行数。所以使用 if (rows[0][0] >= 1):

rows[0]returns第一行,rows[0][0]给出第一行第一列;对于您的 SELECT COUNT(*) 第一列是计数,因此您测试计数是否为 0 或者是否 >= 1。