将golang切片直接插入postgres数组



我在将切片直接插入postgres数组时遇到问题,找不到简单的解决方案。

给定:

favorites := []int{1,2,3,4,5}
// need to 
_, err = db.Exec(fmt.Sprintf("UPDATE users SET favorites = '{%v}';", favorites))

因为输入是"{[1,2,3,4,5]}"而不是"{1,2,4,5}",所以我有一个错误。我使用默认的SQL包;github.com/lib/pq";postgres驱动程序。

您应该使用pq。数组(收藏夹(以正确插入。正如你在源代码中看到的那样

它会像:

favorites := []int{1,2,3,4,5}
query:= "UPDATE users SET favorites = $1;"
_, err = db.Exec(query, pq.Array(favorites))

使用pq.array到相应的golang切片将帮助您插入数组。

q = q.Values(result.Id, result.Text, result.CreatedAt, pq.Array(result.EditHistoryTweetIds))

这里编辑历史TweetId将是golang切片。

最新更新