登录
首页 >  Golang >  Go问答

将数据插入数据库

来源:stackoverflow

时间:2024-03-24 20:00:37 441浏览 收藏

在使用 Go、sqlx、Postgres 和 go-swagger 开发 API 时,开发者希望将验证后的请求正文插入 Postgres 表中。现有方法需要逐个字段指定插入值,而开发者希望找到一种方法可以直接保存结构。本文介绍了一种解决方案,利用 sqlx 中的 NamedExec 方法,允许开发者通过提供一个填充好的结构,一次性将结构保存到表中。

问题内容

我正在使用 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, "[email protected]", "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", "[email protected]"})

今天关于《将数据插入数据库》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>