在Scala中的变量上调用字符串插值器 [英] Calling a string interpolator on a variable in Scala

查看:100
本文介绍了在Scala中的变量上调用字符串插值器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Scala中的类编写一些数据库查询帮助器方法.

I am writing some database query helper methods for my classes in Scala.

select方法旨在从产品"表中删除某些列,这些列指定为所需列的逗号分隔列表(字符串).

This select method is intended to pluck certain columns from the Product table, specified as a comma-seperated list (String) of the desired columns.

我希望能够这样称呼它:Product.select("id, title")

I want to be able to call it like this: Product.select("id, title")

以下代码不起作用:

  def select(columns: String) = { DB.readOnly{ implicit session =>
    sql"select ${columns} from $sqlTable limit 1000".map(row => Product(row)).list.apply()
  }}

但是此代码(仅用于说明目的)确实有效

But this code (for illustration purposes only) does

  def select(columns: String) = { DB.readOnly{ implicit session =>
    var x = sqls"id, title, description, available_online"
    sql"select ${x} from $sqlTable limit 1000".map(row => Product(row)).list.apply()
  }}

现在,显然我不想将列硬编码到该方法中,但是我想使用columns参数字符串来完成此操作(希望您能抓住我的麻烦).如何在列字符串上应用sqls插值器?

Now, obviously I don't want to hard code columns into the method, but i want to do this with the columns parameter string (I hope you catch my drift). How can I apply the sqls interpolator on the columns string?

类似于var x = sqls(columns)

此处,您可以在sqlssql插值器上找到更多信息

Here you can find more info on the sqls and sql interpolators

如果您需要更多信息,请发表评论,感谢您的反馈.

Please comment if you require more information and I'd appreciate your feedback.

推荐答案

您可以改用SQLSyntax#createUnsafely.

这是一个危险的API.我知道您非常了解SQL注入漏洞.

This is a dangerous API. I know you're aware of SQL injection vulnerability so much.

这篇关于在Scala中的变量上调用字符串插值器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆