查询在 psql 中有效,但语法错误 Python with psycopg2

Query works in psql but Syntax error in Python with psycopg2

我有一个在 psql 中运行良好的查询,但在我的程序中生成错误:

sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
cur.execute(sql)

关于它为什么不起作用的任何指示?或者有什么建议,我该如何解决?

这与 PostgreSQLMySQL 查询语法无关 - 这只是 Python:

中的语法错误
>>> sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
  File "<stdin>", line 1
    sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
                                                              ^
SyntaxError: invalid syntax

将查询放入双引号中:

sql = "SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;"

Python 中代码字符串的最佳做法是使用三重引号引起来的字符串,这样更清晰并且可以包含单引号和双引号:

sql = '''
    SELECT id, x, y
    FROM table_name
    WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;
'''

来自manual

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.