简体   繁体   English

您可以在使用模板化 SQL 查询时简化查询吗

[英]Can you simplify a query while using templated SQL queries

Is there a way to simplify this statement as well as access a certain element in the tuple.有没有办法简化这个语句并访问元组中的某个元素。

l = (1,2,3,4)
sql = "INSERT INTO table1 VALUES ('%s', '%s', '%s', '%s') ON DUPLICATE KEY UPDATE id = 3"
cursor.execute(sql, l)

Into something that is more dynamic - I am using this as an example but I have a table with around 30 columns and it seems to be redundant doing it this way.进入更具动态性的内容 - 我以这个为例,但我有一个大约有 30 列的表,这样做似乎是多余的。 I would also like to update some of the fields when there is a duplicate key.当有重复键时,我还想更新一些字段。 Is there a way to index to a particular value, such as the third one in the list and display it like this有没有办法索引特定值,例如列表中的第三个值并像这样显示它

l = (1,2,3,4)
sql = "INSERT INTO table1 VALUES ('%s') ON DUPLICATE KEY UPDATE id = {l[2]}"
cursor.execute(sql,l)

Where "l" will be something that contains the values that will be inserted into the table其中“l”将包含将插入表中的值

You can construct the placeholder string dynamically based on the length of the tuple.您可以根据元组的长度动态构造占位符字符串。

l = (1, 2, 3, 4)
placeholders = ",".join(['%s'] * len(l))
sql = f"INSERT INTO table1 VALUES ({placeholders}) ON DUPLICATE KEY UPDATE id = 3"
cursor.execute(sql, l)

BTW, don't name your variable list , that will replace the stanfard list() function.顺便说一句,不要命名您的变量list ,它将替换标准list()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM