[英]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 我有一个变量row_data = (searchindex, asin, title, browsenode, salesrank, brand, listprice, saleprice)
,这些元素中的任何一个都可能为NULL
,要插入数据库中,我正在使用
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. 但这不是很可扩展,因为我在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. 请不要使用字符串插值来构造SQL,因为这是非常不安全的。 Use the appropriate features in your MySQL library to pass in the values as parameters to the query. 使用MySQL库中的适当功能将值作为参数传递给查询。
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. 也许每隔几个月一次,此时更新您的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. 或者,您可以使用诸如SQLAlchemy之类的系统来为您处理大量此类事务 ,而不必自己编写大量SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.