简体   繁体   English

第一次查询后连接游标返回 None

[英]Connection cursor return None after first query

I'm a newbie in Python and working for the first time with Django.我是 Python 新手,第一次使用 Django。

My connection.cursor() return None after first call.我的 connection.cursor() 在第一次调用后返回 None 。

Here's my problem :这是我的问题:

def request_pc(request):
    body = request.body.decode('utf-8')
    data = json.loads(body)
    if not firstCheck(data['testValue1']):
        return JsonResponse({'error': 'foo'})

    data = secondCheck(data['testValue2'])
    if not data:
        return JsonResponse({'error': 'foo'})

def first_check(testValue1):
    with connection.cursor() as cursor:
        row_count = cursor.execute('''
            SELECT 1
            FROM foo_session
            WHERE value = %s
        ''', [testValue1])
    if 1 == row_count:
        return True
    return False


def second_check(testValue2):
    with connection.cursor() as cursor:
        row_count = cursor.execute('''
            SELECT *
            FROM core_foo2
            WHERE value = %s
        ''', [testValue2])
    res = cursor.fetchone()
    pprint(row_count) // return 1
    pprint(res) // return empty
    if not res:
        return False
    return res

first_check return data and everything is ok first_check 返回数据,一切正常

but

second_check return row_count = 1 and data is empty second_check 返回 row_count = 1 并且数据为空

I have the same problem if I copy/paste the first query on the second...如果我在第二个上复制/粘贴第一个查询,我会遇到同样的问题...

Thank you谢谢

You are here "closing" the cursor before fetching the entry.在获取条目之前,您在这里“关闭”了光标。 By using .fetcone() in the with clause, you prevent that:通过在with子句中使用.fetcone() ,可以防止:

def second_check(testValue2):
    with connection.cursor() as cursor:
        row_count = cursor.execute('''
            SELECT *
            FROM core_foo2
            WHERE value = %s
        ''', [testValue2])
        # ↓ in the with clause
        res = cursor.fetchone()
    pprint(row_count) # return 1
    pprint(res) # return empty
    if not res:
        return False
    return res

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM