【问题标题】:Anorm: Escape Single Quote异常:转义单引号
【发布时间】:2016-05-14 10:10:55
【问题描述】:

我正在使用 anorm 进行简单的 db 粗加工,当输入参数包含单引号时,会出现静默失败问题。例如,用户表中的姓氏“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("'", "''")

提前致谢!

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

【问题讨论】:

    标签: scala anorm


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 2015-05-27
      • 1970-01-01
      相关资源
      最近更新 更多