I am trying to insert data to a table in Postgresql using Psycopg2's execute_values(). However, the job keeps on failing when I use "string composition". Is it possible to use string composition with execute_values() ?:
table='my_tab'
schema='my_schema'
col_lst = ['emp_id', 'emp_name', 'emp_age', 'emp_salary']
rec_lst = [('1234', 'John', 35, 10000), ('5678', 'Mike', 42, 15000), ('3452', 'Jason', 33, 15000)]
query = sql.SQL("INSERT INTO {schema}.{table} ({cols}) VALUES ({values});")
col_str = sql.SQL(', ').join(sql.Identifier(col) for col in col_lst)
place_holders = sql.SQL(', ').join(sql.Placeholder() * len(col_lst))
query = query.format(schema=sql.Identifier(schema), table=sql.Identifier(table), cols=col_str, values=place_holders)
psycopg2.extras_execute_values(cursor, query, rec_lst, page_size=1000)
Error: The query contains more than one '%s' placeholder...
Can anyone please help fix the same.
Thanks
emp_age'should be'emp_age'and is throwing everything else off. Not sure if this is copy/paste error or mistake in actual code? 2)INSERT INTO {schema}.{table} ...can beINSERT INTO {table} ...withtable=sql.Identifier(schema, table).... VALUES %. So you don't need to doplace_holders = ...and...values=place_holders....VALUES %s.