1

I have used ? placeholder to pass list of values in Python for Insert/Update.

Now, I am trying to upsert the records with the help of this answer

Code:

table_name = 'ddf.ddf_actuals'

columns_list = df.columns.tolist()
columns_list_query = f'({(",".join(columns_list))})'
sr_columns_list = [f'Source.{i}' for i in columns_list]
sr_columns_list_query = f'({(",".join(sr_columns_list))})'
up_columns_list = [f'{i}=Source.{i}' for i in columns_list]
up_columns_list_query = f'{",".join(up_columns_list)}'

rows_to_insert = [row.tolist() for idx, row in final_list.iterrows()]
rows_to_insert = str(rows_to_insert).replace('[', '(').replace(']', ')')[1:][:-1]


query = f"MERGE INTO {table_name} as Target \
USING (SELECT * FROM \
(VALUES {rows_to_insert}) \
AS s {columns_list_query}\
) AS Source \
ON Target.stationcode=Source.stationcode AND Target.date=Source.date \
WHEN NOT MATCHED THEN \
INSERT {columns_list_query} VALUES {sr_columns_list_query} \
WHEN MATCHED THEN \
UPDATE SET {up_columns_list_query};"
c.execute(query)

c.commit()

Issue is rows_to_insert has string values with single quotes. I tried to replace single quote with \', but did not work as expected. Since \' is an escape sequence for Python, not for SQL, did not work. Even replacing with '' did not work

Since I am executing list of list, not sure how placeholder ? can be used here

Karthick Raju
  • 757
  • 8
  • 29
  • I had to solve this same problem and posted my solution on the post you linked - here's a link to my response: https://stackoverflow.com/a/64067438/10342097 – Elliot Young Sep 25 '20 at 16:01

0 Answers0