SQL IF语句

时间:2015-06-18 14:40:38

标签: python sql postgresql flask

我正在使用python Flask并且无法理解为什么我会收到错误:

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

这是我的代码:

 > 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

一个简单的插入效果很好但不是if语句。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

因为" ON CONFLICT"在PostgreSQL 9.5中引入了语法,你必须在python中测试行的存在。

如果您对用户标识具有唯一约束,则可以使用例外:

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()

答案 1 :(得分:0)

这不是SQL语法,而是PL/pgSQL程序语言。它主要用于编写functions。您可以将它用于一次性命令,但需要将其放在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
$$

但请注意,如果其他人同时插入/删除ProfilePicture,您的逻辑将无效;您可能会丢失更新,或者为同一userid插入多个记录。避免这种情况是less than straightforward