首页 > 解决方案 > Python 格式化字符串文字返回“SyntaxError:无效语法”

问题描述

我正在使用 python cx_oracle ,当我尝试将变量插入 sql 时:

cursor.executemany(f"INSERT INTO table ({columns}) VALUES ({placeholders })",t)

它返回:

  File "eula_db.py", line 77
    cursor.executemany(f"INSERT INTO table ({columns}) VALUES ({placeholders })",t)
                                                                                       ^
SyntaxError: invalid syntax

标签: python

解决方案


使用 Python 3.6

t.py 包含:

columns = 'abc'
placeholders = ':b'
s = f"INSERT INTO EULA_STG_DATA ({columns}) VALUES ({placeholders })"
print(s)

行为取决于 Python 版本:

$ python --version
Python 2.7.16
$ python t.py 
  File "/Users/cjones/py/so15.py", line 3
    s = f"INSERT INTO EULA_STG_DATA ({columns}) VALUES ({placeholders })"
                                                                        ^
SyntaxError: invalid syntax

使用较新的 Python:

$ python --version
Python 3.9.1
$ python t.py 
INSERT INTO EULA_STG_DATA (abc) VALUES (:b)

推荐阅读