如何通过一个查询插入多行?

时间:2019-03-23 11:55:31

标签: postgresql go

在PostgreSQL中,我有一个非常简单的表,用于存储有关用户与游戏之间的关系的信息。这是我用来插入数据的工作功能。如您所见,它对数据库进行多个SQL查询,我认为这并不好。要通过一个查询插入多行,我需要更改什么?

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.")
}

0 个答案:

没有答案