将数据插入到MyTable表中(包括name、age等字段)。

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

INSERT INTO MyTable (name, age, ...)

问题

如何使用Go的标准 sql包来结构化代码,以便他人可以阅读?

我需要添加很多字段。

result, err := db.Exec(
    "INSERT INTO MyTable (name, age, ...很多字段...) VALUES ($1, $2, ...很多字段...)",
    "gopher",
    27,
    ...很多字段...
)

编辑:额外问题,你能否使用类似这样的方式从db:"..."中提取字段名?

type MyTable struct {
    Age   int64   `db:"age" json:"age"`
    Name  string  `db:"name" json:"name"`
    ....
}
英文:

How can I structure this using the go standard sql package so others can read it?
I need to add many many fields.

result, err := db.Exec(
	"INSERT INTO MyTable (name, age, ...ALLLOOOT...) VALUES ($1, $2, ...ALLLOOOT...)",
	"gopher",
	27,
    ...ALLLOOOT...
)

EDIT: Bonus question, can you use something like this and extract field names from db:"..."?

type MyTable struct {
    Age   int64   `db:"age" json:"age"`
    Name  string  `db:"name" json:"name"`
    ....
}

答案1

得分: 1

有不同的方法可以实现这个,其中一种方法是创建键和值的数组,然后使用它们来迭代并构建带有占位符的查询。

然后,您可以使用可变参数来填充占位符。

代码示例如下:

keys := []string{"your", "keys", ...}
values := []interface{}{1, "two", ...}
placeholders := make([]string, len(values))
for idx := range values {
    placeholders[idx] = "?"
}
query := fmt.Sprintf("INSERT INTO (%s) VALUES (%s)", strings.Join(keys, ", "), strings.Join(placeholders, ", "))

result, err := db.Exec(query, values...)

这个示例展示了类似的用法,只是使用了 fmt.Printf

http://play.golang.org/p/NruF92EJqM

英文:

There are different ways to do this, one of the ways I've done is create arrays of keys and values which you can then use to iterate and build up your query with placeholders.

You would then use variadic arguments to fill the placeholders.

It would look something like this

keys := []string{"your", "keys", ...}
values := []interface{}{1, "two", ...}
placeholders := make([]string, len(values))
for idx := range values {
    placeholders[idx] = "?"
}
query := fmt.Sprintf("INSERT INTO (%s) VALUES (%s)", strings.Join(keys, ", "), strings.Join(placeholders, ", "))

result, err := db.Exec(query, values...)

This playground shows something similar done with fmt.Printf

http://play.golang.org/p/NruF92EJqM

huangapple
  • 本文由 发表于 2016年1月13日 11:05:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/34757726.html
匿名

发表评论

匿名网友

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

确定