Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在djnago的insert查询中动态使用列名_Python_Mysql_Django_Django Views - Fatal编程技术网

Python 如何在djnago的insert查询中动态使用列名

Python 如何在djnago的insert查询中动态使用列名,python,mysql,django,django-views,Python,Mysql,Django,Django Views,在上面的查询中,我希望动态地传递列名,并且%s在值中也不预定义它需要写入多少次 那么,如何根据来自2d数组中html表的数据编写sql查询???我们需要在使用查询之前构建查询。如下 cursor.execute("insert into demoapp_site ('name','firstname','lastname') values (%s,%s,%s)",site_data) field_string = "" value_string = "" # This will string

在上面的查询中,我希望动态地传递列名,并且%s在值中也不预定义它需要写入多少次


那么,如何根据来自2d数组中html表的数据编写sql查询???

我们需要在使用查询之前构建查询。如下

cursor.execute("insert into demoapp_site ('name','firstname','lastname') values (%s,%s,%s)",site_data)
field_string = ""
value_string = ""

# This will string in this format "'field1','field2'"
# Assuming array is in format [["field1", "value1"],..]
# Update the for loop statement based on your input, other lines remain same 
for field, value in my_field_array:
    temp_field_string = "'%s'" % field
    field_string = field_string + temp_field_string + ","
    temp_value_string = "'%s'" % value
    value_string = value_string + temp_value_string + ","

# Removing trailing comma's before passing the values
cmd = "insert into demoapp_site (%s) values (%s)" % (field_string[:-1], value_string[:-1])
cursor.execute(cmd)