Anorm:转义单引号

Anorm: Escape Single Quote

我正在为简单的 db crude 使用 anorm,当输入参数包含单引号时,静默失败会出现问题。例如,用户 table 中的姓氏 "O'Brien" 或 "O'Neill"。我试图在查询中使用双引号来转义单引号,这消除了静默失败,但是数据库条目包含姓氏 "O''Brien" 和 "O''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("'", "''")

提前致谢!

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

使用 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@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()