你怎么知道什么时候GroovyStrings不像字符串那样对待?

Arm*_*and 2 mysql groovy mysql-connector groovy-sql

在尝试修改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.execute "truncate $tableName"
Run Code Online (Sandbox Code Playgroud)

抛出:

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
Run Code Online (Sandbox Code Playgroud)

以下工作没有问题:

sql.execute "truncate $tableName".toString()
Run Code Online (Sandbox Code Playgroud)

这是令人惊讶的.我是否应该预料到这个问题,如果是这样,在什么情况下GroovyStringString实例可能会有不同的对待?

tim*_*tes 5

这里的区别在于Groovy Sql类明确地与GStrings一起使用以确保参数被正确引用(如文档中所述).

所以它将第一个例子转换为

truncate 'my_table'
Run Code Online (Sandbox Code Playgroud)

哪个错了(正如错误解释的那样)

您还可以使用:

sql.execute "truncate ${Sql.expand(tableName)}"
Run Code Online (Sandbox Code Playgroud)