Shamoon
Shamoon

Reputation: 43599

How can I INSERT into a MySQL table in Python with a variable number of columns?

I have a variable row_data = (searchindex, asin, title, browsenode, salesrank, brand, listprice, saleprice) and either of those elements might be NULL, to insert into a database, I'm using

sql = "INSERT INTO table (searchindex,asin,title,browsenode, salesrank, brand, listprice, saleprice) VALUES ('%s','%s','%s','%s', '%s', '%s', '%f', '%f')" % row_data

But that's not very scalable as I add more fields into row_data. Is there any more efficient way to do this?

Thanks

Upvotes: 0

Views: 786

Answers (1)

Kylotan
Kylotan

Reputation: 18449

Please don't use string interpolation to construct SQL, as it is very unsafe. Use the appropriate features in your MySQL library to pass in the values as parameters to the query.

The number of columns in a table should hardly change as your program is developed. Maybe once every few months, at which point it's rarely difficult to update your SQL.

Alternatively you could use a system such as SQLAlchemy which handles a lot of this for you and stops you having to write much SQL yourself.

Upvotes: 3

Related Questions