在Python psycopg2中,如何检查行是否存在?
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():
fetchall()
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如果没有要获取的内容,则返回,对进行测试is not None会为您提供一个方便的布尔值,以直接返回。
fetchone()``None
is not None