简体   繁体   English

如何在具有可变列数的Python中插入到MySQL表中?

[英]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.

相关问题 如何使用Python将从MySQL表中选择的行列成功插入到目标MSSQL表中? - How can I successfully insert row columns selected from MySQL table into a destination MSSQL table using Python? 如何使用python将变量插入MySQL表 - How to insert variable to MySQL table using python 如何使用python更快地将行插入mysql表? - How can I insert rows into mysql table faster using python? 如何使用 Python 将单个数据插入 Mysql 表中? - How can i insert a single data into a Mysql table using Python? 将变量值插入MySql和python中的变量列 - Insert variable values to variable columns in MySql & python 我如何计算表中的列数 - how can i count number of columns in table 如何使用python在MYSQL表中创建变量列 - How to create variable columns in MYSQL table using python 如何在Python中验证变量是数字? - How can I verify that a variable is a number in Python? MySQL/Python - 如何通过向按列排列的第一个 NULL 单元格添加新值来更新表 - MySQL/Python - how can I update a table by adding new values to the first NULL cell poceeding by columns 如何将表存储在变量中,每行作为元素和分隔符,以便在Python中使用BeautifulSoup来区分列? - How can I store a table in a variable with each row as an element and a delimiter to distinguish columns using BeautifulSoup in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM