douyoupingji7238 2019-01-12 00:17
浏览 682
已采纳

如何将JSON对象转换为MySQL行?

I'd like to take a JSON string representing an object from a 3rd party API and insert it into a MySQL table. The JSON object properties match the table fields 1-to-1. There are several hundred columns in this table/JSON object. And there will be a few dozen rows to insert at any time.

I'd rather not make a huge struct. But if I need to, then I'd rather not db.Prepare() an INSERT statement with several hundred "?"s. But if I have to then I'd rather not Have to write a stmt.Exec() with several hundred parameters.

Is there a good way to do this in golang? Or is it just going to be extremely inefficient?

  • 写回答

1条回答 默认 最新

  • dongqiaozhe5070 2019-01-12 00:49
    关注

    Use the following given a slice of valid database field names fieldNames and JSON data data:

    var j map[string]interface{}
    if err := json.Unmarshal(data, &j); err != nil {
        // handle error
    }
    var names []string
    var inserts []string
    var values []interface{}
    for _, n := range fieldNames {
        if v, ok := j[n]; ok {
            names = append(names, n)
            inserts = append(inserts, "?")
            values = append(values, v)
        }
    }
    statement := "insert into yourTable (" +
        strings.Join(names, ", ") +
        ") values (" + strings.Join(inserts, ", ") + ")"
    err := db.Exec(statement, values...)
    

    To avoid SQL injection attacks, it's important to work from a slice of known column names.

    You can query the database to create the fieldNames slice. See Get table column names in MySQL? for the query required.

    If the column names and JSON names are different, then replace the slice with a map where the keys are the column names and the values are the JSON names:

    fieldNames := map[string]string{
      "column1": "json1",
      ... and so on
    }
    
    var j map[string]interface{}
    if err := json.Unmarshal(data, &j); err != nil {
        // handle error
    }
    var names []string
    var inserts []string
    var values []interface{}
    for dbName, jsonName := range fieldNames {
        if v, ok := j[jsonName]; ok {
            names = append(names, dbName)
            inserts = append(inserts, "?")
            values = append(values, v)
        }
    }
    statement := "insert into yourTable (" +
        strings.Join(names, ", ") +
        ") values (" + strings.Join(inserts, ", ") + ")"
    err := db.Exec(statement, values...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败
  • ¥150 计算DC/DC变换器平均模型中的参数mu
  • ¥25 C语言代码,大家帮帮我
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)