0

I'm trying to insert some strings from an array of strings using string formatting.

But for some reason, Python is filling the first %s with the desired string but surrounded by single quotes.

Is there an explicit way to prevent this behavior?

Example:

myString = [['000b',
  '1',
  'Text1',
  '1.74',
  'Text2',
  'None'],
 ['000b',
  '1',
  'TextA',
  '12.92',
  'TextB',
  'None']]

When I run the following:

cursor.executemany("INSERT INTO schema.myTable_%s_name (col1, col2, col3, col4, col5) VALUES (%s, NULLIF(%s,'None')::decimal, NULLIF(%s,'None')::decimal, %s, NULLIF(%s,'None')::int)", myString[0:len(myString)])

the expected behavior is that the table name becomes schema.myTable_000b_name but Python writes schema.myTable_'000b'_name which naturally prevents the SQL from running. How could I specify that I don't want the single quotes to be inserted?

1 Answer 1

1

This does not work the way you think it should.

The executemany procedure creates an SQL statement, and then executes the same statement, binding it to different parameters. This way you can e.g. quickly insert many rows into a table.

This does not allow to run multiple different SQL statements, each with its own parameters. It does not support interpolating table names from parameters; the fact that it sort of tried to work is a curiosity, not a feature.

If you need to insert into many tables, issue as many insert statements. Compute the table name using normal Python interpolation. The DB driver tries to interpret your parameter, found in the middle of a table name, as a varchar constant, properly quoting it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.