Python psycopg2检查行存在 [英] Python psycopg2 check row exists

查看:284
本文介绍了Python psycopg2检查行存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python psycopg2中,如何检查行是否存在?

In Python psycopg2 how can I check if a row exists?

def track_exists(self, track_id):
    cur = self.conn.cursor()
    cur.execute("SELECT fma_track_id FROM tracks WHERE fma_track_id = %s", (track_id,))
    if cur.fetchall() > 0:
        return true
    else:
        return false

当前我正在

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mumu.py", line 38, in track_exists
if cur.fetchall() > 0:
TypeError: 'NoneType' object has no attribute '__getitem__'


推荐答案

不要使用 fetchall()(返回的列表永远不会大于0),请使用 fetchone()

Don't use fetchall() (which returns a list, which is never 'larger than 0'), use fetchone():

def track_exists(self, track_id):
    cur = self.conn.cursor()
    cur.execute("SELECT fma_track_id FROM tracks WHERE fma_track_id = %s", (track_id,))
    return cur.fetchone() is not None

fetchone()返回 None 如果没有要提取的内容,并且针对进行的测试不是无,则为您提供方便的布尔值以直接返回。

fetchone() returns None if there is nothing to fetch, and testing against is not None gives you a handy boolean value to return directly.

这篇关于Python psycopg2检查行存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆