Anorm:Escape Single Quote

时间:2016-05-14 01:35:32

标签: scala anorm

我使用anorm作为简单的db raw,当输入参数包含单引号时,存在静默失败的问题。例如姓氏" O' Brien"或者" O' Neill"在用户表中。我尝试使用双引号来转义查询中的单引号,这会删除静默失败,但数据库条目包含姓氏" O' Brien"和"' Neill"。逃避单引号的正确方法是什么?

代码看起来像(抱歉,请在SO中使用格式标签):

def insertNewUser(user: User): \/[Exception, UUID] = DB.withConnection { implicit connection =>
val updatedRowCount =
  SQL"""insert into user(id, email, first_name, surname)
        values (${user.id}::uuid, ${user.email}, ${sanitiseSqlQueryInput(user.firstName)},
        ${sanitiseSqlQueryInput(user.surname)})""".executeUpdate()
updatedRowCount match {
  case 1 =>
    log.debug(s"New user is successfully created [userId=${user.id.toString}]")
    \/-(user.id)
  case _ => -\/(new Exception(s"""Fail to create new user [id=${user.id.toString}] [email=${user.email}] [user=$user]"""))
}}

def sanitiseSqlQueryInput(s: String): String = s.replace("'", "''")

提前致谢!

我的回复可能有限,因为我还没有发表评论。

1 个答案:

答案 0 :(得分:2)

使用SQL插值器,您不需要。 Anorm为您创建准备好的声明。请注意结果res0中的参数映射:

scala> val name = "O'Neill"
name: String = O'Neill

scala> SQL"""SELECT ${name}"""
res0: anorm.SimpleSql[anorm.Row] = SimpleSql(anorm.SqlQuery$$anon$1@6e7633d,Map(_0 -> ParameterValue(O'Neill)),<function1>,false)
                                                                                  ^
                                                                 // --------------|

您可以简单地写一下:

SQL"""
  insert into user (id, email, first_name, surname) values 
  (${user.id}, ${user.email}, ${user.firstName}, ${user.surname})
   """.executeUpdate()