【问题标题】:Syntax error in SQL IF statementSQL IF 语句中的语法错误
【发布时间】:2015-06-18 14:40:37
【问题描述】:

我正在使用 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 语句。

感谢您的帮助!

【问题讨论】:

标签: python sql postgresql flask


【解决方案1】:

由于 PostgreSQL 9.5 引入了“ON CONFLICT”语法,你必须在 python 中测试该行是否存在。

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

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

【讨论】:

    【解决方案2】:

    这不是 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。

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 2011-09-22
      • 2015-09-08
      • 1970-01-01
      • 2018-08-30
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多