【问题标题】:How can I add multiple table entries with a single json command in python?如何在 python 中使用单个 json 命令添加多个表条目?
【发布时间】:2021-12-12 07:41:55
【问题描述】:

我想使用单个 JSON 输入将多个条目放入表中,但我不知道如何从这里开始。一旦用户声明,我就会到达那里

[
 {
  "VIN": "kjasdfh",
  "Make": "Toyota",
  "model": "Corolla",
  "Year": 1998
 },
 {
  "VIN": "wqeiryu",
  "Make": "Honda",
  "model": "Civic",
  "Year": 1997
 }
]

我不会让第一个有自己的条目,而第二个有另一个条目。

 @app.route('/api/addcar', methods = ['POST']) # This is a post method because the user needs to be able to add info
 def adding_stuff():
     request_data = request.get_json() # Gets the info from the table and converts to JSON format
     new_vin = request_data['VIN']
     new_make = request_data['Make']
     new_year = request_data['Year']
     new_color = request_data['Color']
     sql = "INSERT INTO carsTEST (VIN, Make, Year, Color, username) VALUES ('%s', '%s', %s, '%s')" % (new_vin, new_make, new_year, new_color) # This sql statement will then be uploaded to the databse to add a new record
     conn = create_connection()
     execute_query(conn, sql) # This will execute the query
     return 'Post worked'

【问题讨论】:

标签: python mysql json


【解决方案1】:

您必须将您的 json 数组转换为模型数组(使用序列化程序或您的框架提供的东西)。 或者尝试使用以下内容构建您的原始 sql:

json_data = [
 {
  "VIN": "kjasdfh",
  "Make": "Toyota",
  "model": "Corolla",
  "Color": "red",
  "Year": 1998
 },
 {
  "VIN": "wqeiryu",
  "Make": "Honda",
  "model": "Civic",
  "Color": "white",
  "Year": 1997
 }
]

sql = "INSERT INTO carsTEST (VIN, Make, Year, Color, username) VALUES"

for jo in json_data:
    new_vin = jo['VIN']
    new_make = jo['Make']
    new_year = jo['Year']
    new_color = jo['Color']
    value_sql = "('{}', '{}', '{}', '{}'),".format(new_vin, new_make, new_year, new_color)
    sql = sql + value_sql

sql = sql.rstrip(',') + ";"

print(sql)

编辑1: 该方法应该类似于:

@app.route('/api/addcar', methods=['POST'])
def adding_stuff():
    request_data = request.get_json() # post body must be a json array
    sql = "INSERT INTO carsTEST (VIN, Make, Year, Color) VALUES"
    for jo in request_data:
        new_vin = jo['VIN']
        new_make = jo['Make']
        new_year = jo['Year']
        new_color = jo['Color']
        value_sql = "('{}', '{}', '{}', '{}'),".format(new_vin, new_make, new_year, new_color)
        sql = sql + value_sql
    sql = sql.rstrip(',') + ";"
    conn = create_connection()
    execute_query(conn, sql)  # This will execute the query
    return 'Post worked'

【讨论】:

  • 但是我怎样才能做到这一点,我只是编码后端,我正在等待用户输入 json_data 变量?
猜你喜欢
  • 1970-01-01
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2018-01-23
  • 1970-01-01
相关资源
最近更新 更多