【问题标题】:How to use column name dynamically inside insert query in djnago如何在 django 的插入查询中动态使用列名
【发布时间】:2020-08-04 03:33:55
【问题描述】:
cursor.execute("insert into demoapp_site ('name','firstname','lastname') values (%s,%s,%s)",site_data)

在上面的查询中,我想动态传递列名,而内部值的 %s 也没有预先定义它需要写入多少次

那么,如何根据我的数据编写我的 sql 查询,这些数据来自二维数组中的 html 表??

【问题讨论】:

    标签: python mysql django django-views


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多