【问题标题】:How do you know when GroovyStrings are not treated the same as Strings?你怎么知道 GroovyStrings 什么时候不被当作 Strings 对待?
【发布时间】:2013-03-14 14:11:08
【问题描述】:

我刚刚在尝试修改 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"

抛出:

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

而以下工作没有问题:

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

这令人惊讶。我是否应该预料到这个问题,如果是这样,在什么情况下GroovyStringString 实例可能会被区别对待?

【问题讨论】:

    标签: mysql groovy mysql-connector groovy-sql


    【解决方案1】:

    这里的区别在于 Groovy Sql 类显式使用 GStrings 以确保正确引用参数 (as explained in the documentation)。

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

    truncate 'my_table'
    

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

    你也可以使用:

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

    【讨论】:

    • +1 我遇到了同样的问题,虽然只是使用'asc'和'desc',但这解决了它。它应该被标记为已接受的答案。这让我们发疯,因为将字符串打印到控制台显示了一个完全有效的 SQL 字符串!
    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 2010-11-29
    • 2011-06-09
    • 2018-01-21
    • 2017-02-10
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    相关资源
    最近更新 更多