提取时Posgres Record不会退出

时间:2015-09-10 12:57:02

标签: python postgresql function views

我在循环中从数据库中获取记录行。在循环中还有一些选择查询,其中rerecords不会退出..

我写了这个观点

CREATE view get_application_views AS
SELECT application_id, coalesce(SUM(views),0) as views FROM employer_applicationstats GrOUP BY application_id;

然后在循环中进行此操作..

SELECT views FROM get_application_views WHERE application_id = '5605617';

对于application_id 5605617,没有记录存在,所以我的python脚本引发错误并停止循环。

我该如何处理这种情况?

更新:

def get_application_view(application_id):
    try:
        cursor = connection.cursor()
        sql_query = "SELECT views FROM get_application_views WHERE application_id = '"+str(application_id)+"';"
        cursor.execute(sql_query)
    except Exception as e:
        print e
        status = 0
        return status
    else:
            ver = cursor.fetchone()
            status = ver[0]
        return status

表示application_id = 5605617,

status = ver[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

2 个答案:

答案 0 :(得分:0)

获取任何内容时,

cursor.fetchone()返回None。所以你的原始代码看起来像

def get_application_view(application_id):
    try:
        cursor = connection.cursor()
        sql_query = "SELECT views FROM get_application_views WHERE application_id = '"+str(application_id)+"';"
        cursor.execute(sql_query)
    except Exception as e:
        print e
        status = 0
        return status
    else:
        ver = cursor.fetchone()
        if ver:        
            status = ver[0]
        else:
            status = 0
        return status

另外,我更喜欢从@ celenius的答案中给出的try..except中取出游标对象创建和返回语句。

我们可以将if..else ..块转换为conditional expression status = ver[0] if ver else 0

答案 1 :(得分:0)

在读完postgres函数后,我将我的代码调到这样的东西。

CREATE OR REPLACE FUNCTION get_application_views(application_id integer, OUT views bigint)
RETURNS bigint
LANGUAGE sql
AS $function$
SELECT coalesce((select sum(views) as views from employer_applicationstats where application_id = $1 GROUP BY application_id), 0);
$function$

def get_application_view(application_id):
        cursor = connection.cursor()
        sql_query = "SELECT * FROM get_application_views('{id}')".format(id=application_id)
        try:            
           cursor.execute(sql_query)
        except Exception as e:
           return 0
        else:
            ver = cursor.fetchone()
            status = ver[0]
            return status

感谢@celenius