How do I construct a sql in GO MYSQL with many similar parameters?

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

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 &lt; 10; i++ {
	args = append(args, &quot;param&quot;)
}

q.Query(args...)

More lines of code, but at least you don't have to Ctrl+C/Ctrl+V all the time.

huangapple
  • 本文由 发表于 2016年9月8日 10:41:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/39381791.html
匿名

发表评论

匿名网友

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

确定