简体   繁体   English

SQL IF 语句中的语法错误

[英]Syntax error in SQL IF statement

I'm using python Flask and can't get my head around why i'm getting error:我正在使用 python Flask 并且无法理解为什么我会收到错误:

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.一个简单的插入效果很好,但不是 if 语句。

Appreciate your help!感谢你的帮助!

Since "ON CONFLICT" syntax is introduced in PostgreSQL 9.5, you have to test the existence of the row in python.由于 PostgreSQL 9.5 中引入了“ON CONFLICT”语法,因此您必须在 python 中测试该行是否存在。

If you have a unique constraint on the userid you can use exceptions:如果您对 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)"""
    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.这不是 SQL 语法,而是PL/pgSQL过程语言。 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块中

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;但是请注意,如果其他人同时插入/删除ProfilePicture ,您的逻辑将不起作用; you risk either losing the update, or inserting multiple records for the same userid .您可能会丢失更新,或者为同一个userid插入多条记录。 Avoiding this is less than straightforward .避免这种情况并不简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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