Groovy / Postgres“java.lang.String.positive()”没有方法签名

19

尝试使用JDBC编写一些基本的PostgreSQL代码,最终要集成到用Groovy编写的应用程序中。我已经编写了这个Groovy代码来连接到数据库然后执行语句;但是,我遇到了一个错误,我已经尝试寻找解决方案,但没有成功。这里是相关的Groovy代码部分,以及注释指出错误发生的地方:

def sql = Sql.newInstance(dbUrl, dbUser, dbPassword, dbDriver)

println "Sql Instance: " + sql

sql.execute(
        " DROP TABLE IF EXISTS test;"
        + "CREATE TABLE test ("
            + "id SERIAL,"
            + "word TEXT,"
            + "number INTEGER,"
            + "decimal NUMERIC,"
            + "datetime TIMESTAMP"
            + ");"
 )

def params = ['Hello, World!', 42, 3.14159, null]

sql.execute("INSERT INTO test (word, number, decimal, datetime)"
            + "VALUES (?,?,?,?);", params)

sql.eachRow("SELECT * FROM test;") { row ->
    println "The row Id is: ${row.id}"
        // HERE??
        + "The word is: ${row.word}"
        + "The number is: ${row.number}"
        + "The decimal is: ${row.decimal}"
        + "The date-time is: ${row.datetime}"
}
sql.close()

控制台日志输出:

    Sql实例:groovy.sql.Sql@5aa9e4eb
    行Id为:1
    捕捉到错误:groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: []
    可能的解决方案包括:notify(),tokenize(),size(),size()
    groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: []
    可能的解决方案包括:notify(),tokenize(),size(),size()
        at DatabaseTest$_run_closure1.doCall(DatabaseTest.groovy:34)
        at DatabaseTest.run(DatabaseTest.groovy:31)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
进程以退出代码1结束

你有什么想法,我在哪里出了问题?

2个回答

41

另一个答案给出了我也会推荐的解决方案,但是了解为什么会发生这种情况仍然很有用。

Groovy相当过度地使用了运算符重载。这意味着如果你要写自己的类,你可以重载+运算符来完成许多任务。

然而,在行末使用+与在行首使用它之间存在着区别。

在行末,+被视为二元操作符append(a + b),但在行首,它被视为一元操作符positive+6被视为“正六”)。

如果你编写这个代码,它将工作得更好:

println "The row Id is: ${row.id}" +
    "The word is: ${row.word}" +
    "The number is: ${row.number}" +
    "The decimal is: ${row.decimal}" +
    "The date-time is: ${row.datetime}"

如果你这样做,输出结果会在一行显示,这是因为你没有添加换行符\n

println "The row Id is: ${row.id}\n" +
    "The word is: ${row.word}\n" +
    "The number is: ${row.number}\n" +
    "The decimal is: ${row.decimal}\n" +
    "The date-time is: ${row.datetime}"

现在情况变得越来越糟糕,这就是为什么Groovy的多行String功能很有用,正如其他答案所示。


23

不要使用可怕的字符串拼接!在 Groovy 中有一个很好的替代方法:

println """The row Id is: ${row.id}
    The word is: ${row.word}
    The number is: ${row.number}
    The decimal is: ${row.decimal}
    The date-time is: ${row.datetime}"""

哇,那立刻解决了问题。我猜所有的 SQL 字符串都可以这样做?(或者至少大部分可以) - Phrancis
3
@Phrancis https://dev59.com/nW445IYBdhLWcg3wBVvz#5079914 - tim_yates

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接