Groovy / Postgres "No signature of method: java.lang.String.positive()"

Groovy / Postgres "No signature of method: java.lang.String.positive()"

尝试使用 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 Instance: groovy.sql.Sql@5aa9e4eb
    The row Id is: 1
    Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: []
    Possible solutions: notify(), tokenize(), size(), size()
    groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: []
    Possible solutions: 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)

    Process finished with exit code 1

知道我做错了什么吗?

不要使用可怕的字符串连接!在 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}"""

另一个答案为您提供了我也推荐的解决方案,但最好仍然知道原因 为什么 这个正在发生。

Groovy 过度使用 运算符重载 。这意味着如果您要编写自己的 class,您可以重载 + 运算符来做很多事情。

但是,在行尾和行首使用+是有区别的。

在行尾,+ 被视为 二元运算符 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 的多行字符串功能可以派上用场,如另一个答案所示。