Python 如何在Postgre fresh表中进行空检?

Python 如何在Postgre fresh表中进行空检?,python,sql,postgresql,Python,Sql,Postgresql,现在我的错误是这样的 File "/home/bellvantage/Documents/openerp-7.0/openerp-7/openerp/addons/bpl/bpl.py", line 119, in _max_reg_no res = cr.fetchone()[0] TypeError: 'NoneType' object has no attribute '__getitem__' 我有一个名为bpl_worker的表。我在python代码中调用了一个函数 de

现在我的错误是这样的

  File "/home/bellvantage/Documents/openerp-7.0/openerp-7/openerp/addons/bpl/bpl.py", line 119, in _max_reg_no
    res = cr.fetchone()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'
我有一个名为bpl_worker的表。我在python代码中调用了一个函数

def _max_reg_no(self, cr, uid, context=None):
    res = {}
    cr.execute("""
    select COALESCE(register_no, 'W00001') as reg_no        
    from bpl_worker 
    where id in 
    (select coalesce(max(id),0) from bpl_worker)        
    """)
    rows = cr.fetchall()
    if len(rows) == 0:
        return 'W00001'
    else:
        res = rows[0]
        emp_no = str(res)
        emp_int = emp_no[1:6]
        emp_no_int = int(emp_int)
        result = 'W' + (str(emp_no_int + 1).zfill(4))
        return result        
若表至少有一条记录,那个么它的工作记录和返回记录。在初始级别,无法将if null消息的记录作为输出。 请帮我整理一下这个问题

谢谢

现在我的表如果为空,则发出ok。但在我的记录返回为“W00001”之后 然后错误出现在下面的点

res = cr.fetchone()[0]

首先,整个部分:

CASE 
WHEN register_no IS NULL 
    THEN 'Empty' 
ELSE register_no 
    END
可替换为:

COALESCE(register_no, 'Empty')
Coalesce是一个众所周知的函数,用于处理行中的空值。还有一个IFNULL函数满足相同的需求

就我所知,您希望从空表(即不包含行的表)中获取记录。这不行。您可能希望首先检查查询返回的记录数,这可以通过检查
cr.rowcount
属性,或者尝试获取所有行并检查结果数组的长度来实现:

rows = cr.fetchall()
if len(rows) == 0: return 'Empty'

亲爱的霸权,我的第一期未整理。现在错误出现在其他部分。请检查并建议我-更新后-我认为您不应该在刚刚调用fetchall()时调用fetchone()。有了这些值,只需使用行[0]