0

The table in one database has 30 fields ,when i write some data into table ,how to handle the ? in insert string?

many="? ,"*30
many=many[0:-1]
db_str='INSERT INTO the_table  VALUES (' + many + ');'
con.executemany(db_str, data)

The db_str is ugly for people to use ,how can i make the code look fine.

showkey
  • 482
  • 42
  • 140
  • 295

1 Answers1

1

I think a slightly cleaner way might be to use join:

parameters = ", ".join(["?"] * 30)
query = 'INSERT INTO the_table VALUES(%s);' % parameters
con.executemany(query, data)
icedtrees
  • 6,134
  • 5
  • 25
  • 35
  • it is insecure! http://stackoverflow.com/questions/22586133/why-the-sql-command-is-insecure – showkey Mar 23 '14 at 09:44
  • @it_is_a_literature no, it's not insecure. You just completely failed to understand both this answer and the answer you linked. While using `%s` to directly insert user-entered data into a query is of course insecure and leaves you open for SQL injections, here `%s` is only used to insert the parameter placeholders into the query. This is basically a cleaner alternative to using `+` for string concatenation. – l4mpi Mar 23 '14 at 10:59
  • @it_is_a_literature another way of explaining it is, using %s is insecure when you don't know what you're substituting in. In this case, we defined what we're substituting in (lots of question marks in a string). the `data` is still being prepared properly. – icedtrees Mar 23 '14 at 14:44