Groovy GString issues

后端 未结 4 1839
后悔当初
后悔当初 2020-12-22 09:17

I\'m want use $ macro in groovy GString. When i\'m wrote this code

[\'cdata\',\'tdata\'].each { def sql = \"select * from $it_1\" }

i\'m ge

4条回答
  •  鱼传尺愫
    2020-12-22 09:41

    You can use Groovy's Sql expand feature to help here. The following code will do the trick:

    ['cdata','tdata'].each {table -> def sql = "select * from ${Sql.expand table}_1" }
    

    Using this method is particularly important if you have other parameters in your GString:

    def name = 'Charlie Sheen'
    def tables = ['normalPeople','crazyPeople']
    tables.each { table -> 
        def sqlString = "select * from ${Sql.expand table} where name = ${name}"
        /* Execute SQL here */
    }
    

    In the example above a prepared statement will still be used, and the contents of the 'name' variable will still be handled as a parameter (thus helping to protect you against SQL injection attacks) but the table variable parameter will be expanded correctly.

提交回复
热议问题