How do you know when GroovyStrings are not treated the same as Strings?

泪湿孤枕 提交于 2019-12-12 18:24:27

问题


I've just run into a confusing issue in Groovy while trying to modify a MySQL database. What appears to be identical code throws an Exception unless my GroovyString is explicitly converted to a java.lang.String:

import groovy.sql.Sql
def sql = Sql.newInstance('jdbc:mysql://localhost/test?useUnicode=yes&characterEncoding=UTF-8', 'user', 'pass', 'com.mysql.jdbc.Driver')
def tableName = 'my_table'
sql.execute "truncate $tableName"

throws:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''my_table'' at line 1

Whereas the following works without problems:

sql.execute "truncate $tableName".toString()

This is surprising. Should I have expected this problem, and if so in what situations are GroovyString and String instances likely to be treated differently?


回答1:


The difference here is that the Groovy Sql class explicitly works with GStrings to ensure parameters are properly quoted (as explained in the documentation).

So it converts the first example to

truncate 'my_table'

Which is wrong (as the error explains)

You can also use:

sql.execute "truncate ${Sql.expand(tableName)}"


来源:https://stackoverflow.com/questions/15411647/how-do-you-know-when-groovystrings-are-not-treated-the-same-as-strings

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