开发者

Escape dot from GString

开发者 https://www.devze.com 2023-03-13 10:58 出处:网络
I would like to learn how to escape dot in GString so groovy (1.8) does not treat it as a part of an variable inside sql.execute. I 开发者_Python百科have the following code:

I would like to learn how to escape dot in GString so groovy (1.8) does not treat it as a part of an variable inside sql.execute. I 开发者_Python百科have the following code:

  Map<String, String> dbSettings = [schemaName:"testSchema"];

  String myDbPrefix = dbSetting.schemaName + ".";

  sql.execute "DELETE FROM ${myDbPrefix}myTable"

And I got this error:

Ignoring groovy.lang.MissingPropertyException: No such property: myTable for class: java.lang.String 

Clearly indicating that . was interpreted as part of variable ${myDbPrefix}.


Does escaping the embedded variable help?

     sql.execute "DELETE FROM ${Sql.expand myDbPrefix}myTable"


I got hit by this problem today. GStrings get handled by a special way in GroovySQL. It's mentioned in the javadoc. It does automatic parameter binding.

Each value in the GString will become a parameter (?) which gets set as a JDBC prepared statement parameter.

What a surprise!

I'm going to fix the problem in my application by subclassing the Sql class and overriding the GString handling with plain ".toString()" .

Documented in Groovy wiki:

GString Use Cases - GSQL Another use case for GString is GSQL where parameters can be passed into SQL statements using this same mechanism which makes for a neat way to integrate Groovy with other languages like SQL. GroovySql then converts the expressions to ? and uses a JDBC PreparedStatement and passes the values in, preserving their types.

If you explicitly want to coerce the GString to a String you can use the toString() method. Groovy can also automatically coerce GStrings into Strings for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消