Search code examples
pythonsqlitepython-3.7

Workaround for the ? of sqlite3.Cursor instance


I have a table with 16 columns and I would like to replace the syntax of the executemany method, which is:

# DATABASE is of type sqlite3.Cursor 
# data is of type List[List]
DATABASE.executemany(
          "INSERT INTO table_name VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", data
                      )
DATABASE_CONNECTION.commit()

with something more compact. I don't want to repeat the question mark 16 times. Is there a solution for this ?


Solution

  • You can construct the sql statement lik ethis:

    sql = "INSERT INTO table_name VALUES (" + ("?," * len(data)).strip(",") + ")"
    

    so that you get "?," repeated as many times as the number of items in data and use it:

    DATABASE.executemany(sql, data)