Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 如何通过一个查询插入多行?_Postgresql_Go - Fatal编程技术网

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

Postgresql 如何通过一个查询插入多行?,postgresql,go,Postgresql,Go,在PostgreSQL中,我有一个非常简单的表,用于存储有关用户和游戏之间关系的信息。这是一个用于插入数据的工作函数。正如您所看到的,它对数据库进行多个SQL查询,我认为这并不优雅。要用一个查询插入多行,需要更改什么 var CreateRelationship = func(responseWriter http.ResponseWriter, request *http.Request) { userID := mux.Vars(request)["user_id"] t

在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.")
}
var CreateRelationship=func(responseWriter http.responseWriter,request*http.request){
userID:=mux.Vars(请求)[“用户id”]
类型RequestBody结构{
Games[]int`json:“游戏”`
}
requestBody:=requestBody{}
解码器:=json.NewDecoder(request.Body)
如果错误:=decoder.Decode(&requestBody);错误!=nil{
utils.ResponseWithError(responseWriter,http.StatusBadRequest,err.Error())
返回
}
对于i:=0;i