gpt4 book ai didi

postgresql - 将字符串数组插入 postgres 文本数组字段

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:41 26 4
gpt4 key购买 nike

我正在尝试使一篇文章可标记。

文章表:

type Article struct {
ID int64
Body string
Tags string
}

准备值:

tags := r.FormValue("tags")
tagArray := fmt.Sprintf("%q", strings.Split(tags, ", ")) // How do I make use of this?

t := Article{
Body: "this is a post",
Tags: `{"apple", "orange"}`, // I have to hard code this for this to work.
}
if err := t.Insert(Db); err != nil {
// Error handling
}

数据库查询:

func (t *Article) Insert(db *sqlx.DB) error {
nstmt, err := db.PrepareNamed(`INSERT INTO articles
(body, tags)
VALUES (:body, :tags)
RETURNING *;
`)
if err != nil {
return err
}
defer nstmt.Close()

err = nstmt.QueryRow(t).StructScan(t)
if err, ok := err.(*pq.Error); ok {
return err
}
return err
}

标签字段的 Postgres 设置:

tags character varying(255)[] DEFAULT '{}',

看来我必须对标签的值进行硬编码才能使其正常工作。否则我会得到这样的错误:

pq: missing dimension value
OR
pq: array value must start with "{" or dimension information

如何使用 tagArray

有用的引用:https://gist.github.com/adharris/4163702

最佳答案

您需要使用正确的数组输入格式来格式化您的标签,与您的硬编码值相同。

如果标签不包含任何需要以不同于 strconv.Quote 对它们进行转义的方式进行转义的特殊字符,则以下代码将起作用:

tags := "apple, orange"
tagArray := strings.Split(tags, ", ")
for i, s := range tagArray {
tagArray[i] = strconv.Quote(s)
}
final := "{" + strings.Join(tagArray, ",") + "}"

关于postgresql - 将字符串数组插入 postgres 文本数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29745460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com