gpt4 book ai didi

go - 将请求正文插入数据库

转载 作者:行者123 更新时间:2023-12-01 22:38:45 25 4
gpt4 key购买 nike

我正在使用Go,SQLX,postgres和go-swagger开发API。

在POST方法处理程序中,我获得了由swagger定义和验证的类型的请求正文。
验证后,我想将其插入到postgres表中。

除了以下片段外,我没有找到太多有关该主题的文档:

sqlStatement := `
INSERT INTO users (age, email, first_name, last_name)
VALUES ($1, $2, $3, $4)
RETURNING id`
id := 0
err = db.QueryRow(sqlStatement, 30, "jon@calhoun.io", "Jonathan", "Calhoun").Scan(&id)

这意味着我需要描述要保留的结构的每个字段。

有没有一种方法仅将结构保存在表中?
db.save(struct)

最佳答案

这是in the examples in the README:

// Named queries can use structs, so if you have an existing struct (i.e. person := &Person{}) that you have populated, you can pass it in as &person
tx.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "jane.citzen@example.com"})

关于go - 将请求正文插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60492020/

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