解压 f 字符串中不带“'”的综合列表

Unpacking Comprehensed list without " ' " in f strings

我正在尝试制作一个具有列表理解力的 sql query。首先我取这样的列名

COLUMNS_ONE = ["id INT(6)", "firstname VARCHAR(30)"]
COLUMN_NAMES_ONE = [name.split(" ")[0] for name in COLUMNS_ONE]
print(COLUMN_NAMES_ONE)

>>> ["id", "firstname"]

接下来我尝试为 mysql 创建一个 sql query 变量,就像这样

f"INSERT INTO {TABLE_NAMES[0]} ({*COLUMN_NAMES_ONE,}) VALUES (%s, %s)"

抛出

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '('id', 'firstname')) VALUES (6, 'Marcel')' at line 1

query 插入的不是 (id, firstname),而是 ('id', 'firstname')。 有没有办法以某种方式摆脱 '

您可以使用 join() 代替:

COLUMNS_ONE = ["id INT(6)", "firstname VARCHAR(30)"]
COLUMN_NAMES_ONE = [name.split(" ")[0] for name in COLUMNS_ONE]

f"INSERT INTO Table ({', '.join(COLUMN_NAMES_ONE)}) VALUES (%s, %s)"

# 'INSERT INTO Table (id, firstname) VALUES (%s, %s)'

您可以通过 , 加入列表:

print(f"INSERT INTO Table ({', '.join(COLUMN_NAMES_ONE)}) VALUES (%s, %s)")