我刚刚开始使用Anorm,偶然发现了一个奇怪的行为。当我尝试执行以下操作时:
val userTableName: String = "User"
SQL("INSERT INTO {userTableName} (email, forename, surname, refreshToken) VALUES ({email}, {forename}, {surname}, {refreshToken})")
.on("userTableName" -> userTableName,
"email"->email,
"forename"->forename,
"surname"->surname,
"refreshToken"->refreshToken).executeInsert()
我出现以下错误:
play.api.Application$$anon$1: Execution exception[[JdbcSQLException: Syntax error in SQL statement "INSERT INTO ?[*] (EMAIL, FORENAME, SURNAME, REFRESHTOKEN) VALUES (?, ?, ?, ?) "; expected "identifier"; SQL statement:
INSERT INTO ? (email, forename, surname, refreshToken) VALUES (?, ?, ?, ?) [42001-175]]]
at play.api.Application$class.handleError(Application.scala:296) ~[play_2.11-2.3.8.jar:2.3.8]
at play.api.DefaultApplication.handleError(Application.scala:402) [play_2.11-2.3.8.jar:2.3.8]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$14$$anonfun$apply$1.applyOrElse(PlayDefaultUpstreamHandler.scala:205) [play_2.11-2.3.8.jar:2.3.8]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$14$$anonfun$apply$1.applyOrElse(PlayDefaultUpstreamHandler.scala:202) [play_2.11-2.3.8.jar:2.3.8]
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36) [scala-library-2.11.1.jar:na]
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "INSERT INTO ?[*] (EMAIL, FORENAME, SURNAME, REFRESHTOKEN) VALUES (?, ?, ?, ?) "; expected "identifier"; SQL statement:
INSERT INTO ? (email, forename, surname, refreshToken) VALUES (?, ?, ?, ?) [42001-175]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:332) ~[h2-1.3.175.jar:1.3.175]
at org.h2.message.DbException.getSyntaxError(DbException.java:197) ~[h2-1.3.175.jar:1.3.175]
at org.h2.command.Parser.readIdentifierWithSchema(Parser.java:2926) ~[h2-1.3.175.jar:1.3.175]
at org.h2.command.Parser.readTableOrView(Parser.java:5049) ~[h2-1.3.175.jar:1.3.175]
at org.h2.command.Parser.parseInsert(Parser.java:995) ~[h2-1.3.175.jar:1.3.175]
如果我对表名进行硬编码
SQL("INSERT INTO User (email, forename, surname, refreshToken) VALUES ({email}, {forename}, {surname}, {refreshToken})")
.on("email"->email,
"forename"->forename,
"surname"->surname,
"refreshToken"->refreshToken).executeInsert()
它有效。我解决了这个问题,但最好不要为了重构原因对表名进行硬编码。为什么我不能在这种情况下使用Anorm的动态映射功能?
答案 0 :(得分:2)
正如m-z所说,语法{placeholder}
仅适用于参数(后跟.on("placeholder", value)
)。
您可以将纯字符串插值与此语法SQL(s"SELECT $table ... {id}")
混合使用。