简体   繁体   中英

Syntax error in SQL IF statement

I'm using python Flask and can't get my head around why i'm getting error:

ProgrammingError: syntax error at or near "IF"
LINE 1: IF SELECT count(*) FROM ProfilePicture WHERE userid =

Here is my code:

 > def updateProfilePicture(filename, image, userid):
    >     cursor = getCursor()
    >     binary = psycopg2.Binary(image)
    >     data = (userid, filename, binary, userid, filename, binary, userid)
    >     #SQL = """INSERT INTO ProfilePicture(id, image, userid)
    >      #                   VALUES    (%s, %s, %s)"""
    >     SQL = """IF SELECT count(*) FROM ProfilePicture WHERE userid = %s > 0 
    >     THEN
    >         UPDATE ProfilePicture SET id = %s, image = %s WHERE userid = %s
    >     ELSE
    >         INSERT INTO ProfilePicture(id, image, userid) VALUES (%s, %s, %s)
    >     END IF"""
    >     print cursor.mogrify(SQL, data)
    >     cursor.execute(SQL, data)
    >     cursor.connection.commit()
    >     cursor.close()
    >     return

A simple insert works well but not the if statement.

Appreciate your help!

Since "ON CONFLICT" syntax is introduced in PostgreSQL 9.5, you have to test the existence of the row in python.

If you have a unique constraint on the userid you can use exceptions:

def updateProfilePicture(filename, image, userid):
    cursor = getCursor()
    binary = psycopg2.Binary(image)
    data = (userid, filename, binary, userid, filename, binary, userid)
    SQL = """INSERT INTO ProfilePicture(id, image, userid) VALUES    (%s, %s, %s)"""
    try:
        cursor.execute(SQL, data)
    except:
        cursor.rollback()
        SQL = """UPDATE ProfilePicture SET id = %s, image = %s WHERE userid = %s"""
        cursor.execute(SQL, data)
    cursor.connection.commit()
    cursor.close()

That's not SQL syntax, it's the PL/pgSQL procedural language. It's primarily used to write functions . You can use it for a one-off command, but you need to put it in a DO block :

DO $$
BEGIN 
  IF (SELECT count(*) FROM ProfilePicture WHERE userid = %s) > 0 THEN
    UPDATE ProfilePicture SET id = %s, image = %s WHERE userid = %s;
  ELSE
    INSERT INTO ProfilePicture(id, image, userid) VALUES (%s, %s, %s);
  END IF;
END
$$

Note, however, that your logic will not work if someone else is inserting into/deleting from ProfilePicture at the same time; you risk either losing the update, or inserting multiple records for the same userid . Avoiding this is less than straightforward .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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