Groovy GString issues

半腔热情 提交于 2019-11-28 12:45:45

问题


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 get error unknown property $it_

ok, i'm rewrite it

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

then i'm get unwanted quotes in result string - "select * from 'cdata'_1"

Question is how i'm can use $-macro in GString to achive "select * from cdata_1" result string?


回答1:


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.




回答2:


If the quotes are not from your IDE, or whatever you're evaluating your code in, you can do this:

['cdata','tdata'].each { def sql = "select * from ${it.replaceAll("'","")}_1" } 



回答3:


groovy:000> ['cdata','tdata'].each { def sql = "select * from ${it}_1"; println sql }
select * from cdata_1
select * from tdata_1
===> [cdata, tdata]

I dont see any quotes... that is why I was asking for clarification




回答4:


Real answer was behind the question, so I'm sorry.
Groovy SQL makes parameterized query from GString, so after I had defined GString

def sql = "select * from ${it}_1";

I passed it to Groovy SQL and when I tried to execute the query, the actual query was

"select * from :?_1";

Of cource this drives MSSQL crazy.
Thanks to you all again, maybe someone will find this useful.



来源:https://stackoverflow.com/questions/1621242/groovy-gstring-issues

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!