您如何知道GroovyStrings何时不像Strings一样对待? [英] How do you know when GroovyStrings are not treated the same as Strings?
问题描述
在尝试修改MySQL数据库时,我刚刚在Groovy中遇到了一个令人困惑的问题。除非我的 GroovyString
显式转换为 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.executetruncate $ tableName
抛出:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,在第1行'my_table'附近使用正确的语法
以下工作没有问题:
sql.executetruncate $ tableName.toString()
这是令人惊讶的。我是否应该预料到这个问题,如果是的话,在什么情况下可能会被区别对待 GroovyString
和字符串
实例。
这里的区别在于Groovy Sql类显式地与GStrings协同工作,以确保参数被正确引用(如文档中所述)。
<因此,它将第一个示例转换为
truncate'my_table'
哪一个错误(如错误解释)
您也可以使用:
sql.executetruncate $ {Sql.expand(tableName)}
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?
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)}"
这篇关于您如何知道GroovyStrings何时不像Strings一样对待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!