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


评论