Python psycopg2 check row exists

后端 未结 4 1853
情深已故
情深已故 2021-01-17 15:13

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 FRO         


        
4条回答
  •  滥情空心
    2021-01-17 15:18

    Using exists will allow Postgresql to stop searching at the first occurrence in instead of searching until exhausted:

    exists_query = '''
        select exists (
            select 1
            from tracks
            where fma_track_id = %s
        )'''
    cursor.execute (exists_query, (track_id,))
    return cursor.fetchone()[0]
    

    Another advantage is that it will always return a single row containing a boolean value which can be used directly without further interpretation.

提交回复
热议问题