Question

I know that it's possible to insert many column values in a SQLite database using a variable with a tuple of values ('2006-03-28', 'BUY', 'IBM', 1000, 45.00) and a corresponding placeholder (?, ?, ?, ?, ?) in the query string. I am creating the value tuples dynamically in my program and they may hold up to ~300 values. I am wondering if there is a safe (with respect to SQL injection attacks) way to dynamically generate corresponding the placeholder tuple string (?, ?, ?, ...) for the query string? I ask this to avoid tediously counting, adding and deleting ?s as my database structure and value tuples change throughout development. Thanks for your thoughts.

Was it helpful?

Solution

Build a string based on the number of items in your values, eg:

def place_holder(values):
    return '({})'.format(', '.join('?' * len(values)))

values = ['a', 'b', 'c']
ph = place_holder(values)
# (?, ?, ?)

Then something like:

your_cursor.execute('insert into your_table values {}'.format(ph), values)

If it doesn't meet your schema, you'll have issues, but that's another problem...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top