对于简单的db原油,我使用anorm,当输入参数包含单引号时,存在一个无声失败的问题。例如在用户表中姓“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("'", "''")提前感谢!
我的回应可能是有限的,因为我还不能发表评论。
发布于 2016-05-14 02:10:55
使用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()https://stackoverflow.com/questions/37221552
复制相似问题