Unpacking Comprehensed list without " ' " in f strings

70 views Asked by At

I'm trying to make a sql query with list comprehension. First I take a column names like this

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"]

Next I'm trying to make an sql query variable for mysql like this

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

which throws

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

saying that the query is inserted not like (id, firstname), but ('id', 'firstname'). Is there a way to get rid of that ' somehow?

2

There are 2 answers

0
Mark On BEST ANSWER

You could use join() instead:

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)'
0
Wasif On

You can join the list with , :

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