Issue in substituting values in a string in python 3.7

Viewed 38

I am new in Python. I am trying to form SQL insert query as follows:

table_name = kwargs['table_name']
sql = f"INSERT INTO {table_name} (col1, col2) VALUES (%s, %s)"
params = []
for k, v in my_dict.items():
    params.append([v, k])

for param in params:
     sql = sql % param <---IN THIS LINE I AM GETTING ERROR TypeError: not enough arguments for format string

I know here it is treating param as a single item, that's why I am getting this issue, but I am not getting how to solve this.

Basically in each iteration I want to form following insert sql query:

insert into mytable (col1, col2) VALUES (k1, v1)

I am not able to figure out how to do this.

3 Answers

Use sql = sql % (param[1],param[0]) instead of sql = sql % param

What you should do is

table_name = kwargs['table_name']
sql = f"INSERT INTO {table_name} (col1, col2) VALUES "
params = []

for k, v in my_dict.items():
    params.append("({}, {})".format(k, v))

sql += ', '.join(params)

print(sql)

This way, you are sure to add a ('<value 1>', '<value 2>') string to the query for each and every element in your dict of values.

Related