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

Phr*_*cis 6 groovy

尝试使用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()
Run Code Online (Sandbox Code Playgroud)

控制台日志说:

    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

知道我做错了什么吗?

Sim*_*erg 22

对方的回答给你的解决方案,我也建议,但它可以很好地仍然知道原因,为什么发生这种情况.

Groovy 过度使用运算符重载.这意味着如果您要编写自己的类,则可以使+运算符重载以执行许多操作.

但是,+在一行的结尾和一行的开头使用之间存在差异.

在一行的末尾,+被视为二元运算符 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}"
Run Code Online (Sandbox Code Playgroud)

但是,如果你这样做,你会得到一行输出,那是因为你没有添加换行符, \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}"
Run Code Online (Sandbox Code Playgroud)

现在事情开始变得更加丑陋,这就是为什么Groovy的多行字符串功能可以派上用场,如另一个答案所示.


inj*_*eer 11

不要使用可怕的字符串连接!在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}"""
Run Code Online (Sandbox Code Playgroud)

  • @Phrancis http://stackoverflow.com/questions/5079797/whats-wrong-with-groovy-multi-line-string/5079914#5079914 (2认同)