dongyirong3564 2019-03-23 11:55
浏览 38

如何通过一个查询插入多行? [重复]

This question already has an answer here:

In PostgreSQL I have a pretty simple table where I store information about relationships between users and games. Here is a working function which I use to insert data. As you can see it makes multiple SQL queries to the database which is not elegant I think. What do I need to change to insert multiple rows with one query?

var CreateRelationship  = func(responseWriter http.ResponseWriter, request *http.Request) {
    userID := mux.Vars(request)["user_id"]

    type RequestBody struct {
        Games []int `json:"games"`
    }

    requestBody := RequestBody{}

    decoder := json.NewDecoder(request.Body)

    if err := decoder.Decode(&requestBody); err != nil {
        utils.ResponseWithError(responseWriter, http.StatusBadRequest, err.Error())
        return
    }

    for i := 0; i < len(requestBody.Games); i++ {
        if _, err := database.DBSQL.Exec("INSERT INTO users_games_relationship (user_id, game_id) VALUES ($1, $2);", userID, requestBody.Games[i]); err != nil {
            utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
            return
        }
    }

    utils.ResponseWithSuccess(responseWriter, http.StatusOK, "All new records successfully created.")
}
</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 docker里部署springboot项目,访问不到扬声器
    • ¥15 netty整合springboot之后自动重连失效
    • ¥15 悬赏!微信开发者工具报错,求帮改
    • ¥20 wireshark抓不到vlan
    • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
    • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥15 键盘指令混乱情况下的启动盘系统重装
    • ¥40 复杂的限制性的商函数处理