使用sqlx插入行,是否可以避免显式列出字段?

huangapple go评论85阅读模式
英文:

insert rows with sqlx, is it possible to avoid listing the fields explicitly?

问题

我正在使用sqlx库,如下所示:

type MyData struct {
    Field1 string `json:"db:field1"`
    Field2 string `json:"db:field2"`
}

...

res, err := db.Exec("INSERT INTO XXX (field1, field2) VALUES (?, ?)", data.XX, data.XX)

是否可以避免显式指定"field1, field2",让sqlx自动创建查询和绑定,例如:

db.Exec2("table_name", data)

我没有找到相关的方法来实现这一点。

英文:

I'm using sqlx library like the following:

type MyData {
    Field1 string `json:"db:field1"`
    Field2 string `json:"db:field2"`
}

...

res, err := db.Exec("INSERT INTO XXX (field1, field2) VALUES (?, ?)", data.XX, data.XX)

Is it possible to avoid specifying "field1, field2" explicitly, and let sqlx create the query and binding automatically, e.g

db.Exec2("table_name", data)

I didn't find a relevant method to do that.

答案1

得分: 1

不。包sqlx只是DB驱动的一个包装器,它不是ORM。它期望用户提供有效的SQL查询字符串。你可以通过编程方式构建查询字符串,并使用reflect包设计一些方法,从结构标签中构建列名,但为什么要重新发明轮子呢?使用较低级别的包sqlx的优势正是为了在不引入ORM框架的情况下维护自己的查询。而使用ORM则相反。

相反,Gorm具有一组约定,可以直接满足你的需求。你甚至不需要指定db标签:

GORM更喜欢约定而不是配置,默认情况下,GORM使用ID作为主键,将结构体名称转为蛇形命名作为表名,蛇形命名作为列名,并使用CreatedAt、UpdatedAt跟踪创建/更新时间。

type MyData struct {
    Field1 string `json:"field1"`
    Field2 string `json:"field2"`
}

data := MyData{
    Field1: "foo",
    Field2: "bar",
}

result := db.Create(&data)
// 生成的SQL语句类似于:
// INSERT INTO my_datas (field1, field2) VALUES ('foo', 'bar')
英文:

No. The package sqlx is just a wrapper around the DB driver. It is not an ORM. It expects user-supplied, valid SQL query strings. You may construct the query strings programmatically, and design some method that builds the column names from struct tags using reflect package, but why reinventing the wheel? The advantage of using a lower-level package as sqlx is exactly to maintain your own queries in exchange for not introducing an ORM framework in your codebase. With an ORM instead it is the other way around.

Gorm instead has a set of conventions that do what you want out of the box. You wouldn't even have to specify the db tags:

> GORM prefer convention over configuration, by default, GORM uses ID as primary key, pluralize struct name to snake_cases as table name, snake_case as column name, and uses CreatedAt, UpdatedAt to track creating/updating time

type MyData {
    Field1 string `json:"field1"`
    Field2 string `json:"field2"`
}

data := MyData {
    Field1: "foo", 
    Field2: "bar",
}

result := db.Create(&data) 
// results in something like this:
// INSERT INTO my_datas (field1, field2) VALUES ('foo', 'bar')

huangapple
  • 本文由 发表于 2021年11月12日 09:54:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/69937069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定