如何用参数执行sql查询?

时间:2016-12-06 13:10:08

标签: mysql scala playframework scalikejdbc

val resultList: List[List[String]] =
  sql"""
       select * from exchange_transaction
     """
    .map(
      rs =>
        List(
          rs.string("transaction_id")
        )
    )
    .list()
    .apply()

执行上面的代码,没关系 但是这个sql" select * from exchange_transaction"不固定。 我希望这个sql像一个参数,如follow(简写代码.....)

def findMemberList(segmentExecuteSql: String
    val resultList: List[List[String]] =
      sql"""
           $segmentExecuteSql
         """
        .map(
          rs =>
            List(
              rs.string("transaction_id")
            )
        )
        .list()
        .apply()

但执行后出现错误 消息是

[error] s.StatementExecutor$$anon$1 - SQL execution failed (Reason: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''select * from  exchange_transaction'' at line 1
Query is : 
           'select * from  exchange_transaction'
         ):

   'select * from  exchange_transaction'

我应该怎么做,如何修复异常?

2 个答案:

答案 0 :(得分:0)

您可以尝试将resultList转换为函数:

import scalikejdbc.SQL

def resultList(sqlQuery: String): List[List[String]] =
  SQL(sqlQuery)
    .map(
      rs =>
        List(
          rs.string("transaction_id")
        )
    )
    .list()
    .apply()

答案 1 :(得分:0)

val resultList: List[List[String]] =
  SQL(segmentExecuteSql)
    .map(
      rs =>
        List(
          rs.string("transaction_id")
        )
    )
    .list()
    .apply()