0

I've read the advice here about using parametrized execute call to do all the SQL escaping for you, but this seems to work only when you know the number of columns in advance.

I'm looping over CSV files, one for each table, and populating a local DB for testing purposes. Each table has different numbers of columns, so I can't simply use:

sql = "INSERT INTO TABLE_A VALUES (%s, %s)"
cursor.execute(sql, (val1, val2))

I can build up an sql statement as a string quite flexibly, but this doesn't give me the use of cursor.execute's SQL-escaping facilities, so if the input contains apostrophes or similar, it fails.

It seems like there should be a simple way to do this. Is there?

Community
  • 1
  • 1
James Bradbury
  • 1,708
  • 1
  • 19
  • 31
  • Can you provide an example of the case when escaping doesn't work for you? – Vader Jun 01 '15 at 09:19
  • An alternate way is to [escape](http://www.sqlite.org/lang_expr.html) the apostrophes at the source (CSV files) itself by replacing all single apostrophes with double apostrophes. This is just a workaround to save your time. – bprasanna Jun 01 '15 at 10:46

1 Answers1

3

If you know the number of parameters, you can create a list of them:

count = ...
sql = "INSERT INTO ... VALUES(" + ",".join(count * ["?"]) + ")"
params = []
for i in ...:
    params += ['whatever']
cursor.execute(sql, params)
CL.
  • 173,858
  • 17
  • 217
  • 259