2015-04-22 93 views
2

我剛開始使用Anorm並且偶然發現了一個奇怪的行爲。當我嘗試做到以下幾點:Scala Play 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的動態映射功能?

+1

您不能在預準備語句中使用表名,只能使用實際值。 –

+0

[將模式名稱作爲變量傳遞給查詢的最佳方式]的可能重複(http://stackoverflow.com/questions/29028122/best-way-to-pass-the-schema-name-as-a-可變 - 一個查詢) – cchantep

回答

2

正如m-z所述,語法{placeholder}僅適用於參數(當後跟.on("placeholder", value)時)。

您可以將純字符串插值與此語法SQL(s"SELECT $table ... {id}")混合。