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

熊孩纸 阅读:190 2025-06-02 22:19:02 评论:0

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


标签:数据库
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号