gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:54:39 25 4
gpt4 key购买 nike

尝试使用 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 过度使用运算符重载。这意味着,如果您要编写自己的类,则可以重载 + 运算符来执行许多操作。

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

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

关于Groovy/Postgres "No signature of method: java.lang.String.positive()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31044673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com