开发者

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜