英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论