-2

我正在使用 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)
4

1 回答 1

3

在 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"})
于 2020-03-02T15:42:21.677 回答