英文:
How do I construct a sql in GO MYSQL with many similar parameters?
问题
我目前正在使用GO MySQL,我遇到了一个情况,其中SQL包含许多相似的参数。
stmt, err := db.Prepare( SELECT id FROM questions WHERE description like '%?%' UNION SELECT id FROM books WHERE description like '%?%' UNION SELECT id FROM sites WHERE description like '%?%'
)
param := "golang"
stmt.Query(param, param, param)
我的实际SQL中有大约10个类似的golang
参数和一个重复出现几次的第二个参数。位置参数是构建SQL的唯一方法吗?
英文:
I am currently using GO MySQL and I have a case where the sql contains many similar parameter.
stmt, err := db.Prepare(`
SELECT id
FROM questions
WHERE description like '%?%'
UNION
SELECT id
FROM books
WHERE description like '%?%'
UNION
SELECT id
FROM sites
WHERE description like '%?%'`)
param := "golang"
stmt.Query(param, param, param)
My real life sql has about 10 similar parameters of golang
and a 2nd parameter that repeats itself a few times. Is the positional parameter the only way to construct the sql?
答案1
得分: 0
你可以使用扩展运算符:
args := make([]string, 0)
for i := 0; i < 10; i++ {
args = append(args, "param")
}
q.Query(args...)
代码行数增加了,但至少你不必一直按Ctrl+C/Ctrl+V。
英文:
You can use the spread operator:
args := make([]string, 0)
for i := 0; i < 10; i++ {
args = append(args, "param")
}
q.Query(args...)
More lines of code, but at least you don't have to Ctrl+C/Ctrl+V all the time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论