通过替换相同的子字符串来格式化字符串。

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

Formatting the string by substitute the same substring

问题

我有一段代码,看起来像这样:

const query = `select * 
               from %s.dbo.table1 
               join %s.dbo.table2
                 on ....
               join %s.dbo.table3
                 on ....
               join %s.dbo.table4
                 on ....`

 fmt.Sprintf(query, dbName, dbName, dbName, dbName)

我通过将数据库名称插入到所有%s出现的位置来创建一个SQL查询。有没有更好的方法在不重复使用dbName的情况下完成这个操作?

英文:

I have a code which looks like:

const query = `select * 
               from %s.dbo.table1 
               join %s.dbo.table2
                 on ....
               join %s.dbo.table3
                 on ....
               join %s.dbo.table4
                 on ....`

 fmt.Sprintf(query, dbName, dbName, dbName, dbName)

I just create a SQL query by inserting the database name to all %s occurrences. Is the a better way to do it without repeating dbName ?

答案1

得分: 6

使用%[1]s

const query = `select * 
           from %[1]s.dbo.table1 
           join %[1]s.dbo.table2
             on ....
           join %[1]s.dbo.table3
             on ....
           join %[1]s.dbo.table4
             on ....`
q := fmt.Sprintf(query, dbName)

Playground: https://play.golang.org/p/2DDiGfxLPk.

文档:https://golang.org/pkg/fmt/.

例如,

 fmt.Sprintf("%[2]d %[1]d\n", 11, 22)

将返回"22 11",而

 fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)

等同于

 fmt.Sprintf("%6.2f", 12.0)

将返回" 12.00"。(...)

英文:

Use %[1]s:

const query = `select * 
           from %[1]s.dbo.table1 
           join %[1]s.dbo.table2
             on ....
           join %[1]s.dbo.table3
             on ....
           join %[1]s.dbo.table4
             on ....`
q := fmt.Sprintf(query, dbName)

Playground: https://play.golang.org/p/2DDiGfxLPk.

Documentation: https://golang.org/pkg/fmt/.

>For example,
>
> fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
>
>will yield "22 11", while
>
> fmt.Sprintf("%[3].[2][1]f", 12.0, 2, 6)
>
>equivalent to
>
> fmt.Sprintf("%6.2f", 12.0)
>
>will yield " 12.00". (…)

huangapple
  • 本文由 发表于 2017年8月28日 21:03:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45919758.html
匿名

发表评论

匿名网友

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

确定