def insertToTableSQLQuery(tableName: String, columnDefinitions: Seq[ColumnDefinition], rowData: ListBuffer[Any]): Future[Int] = db.run {
val columns = columnDefinitions.map(_.name).mkString(", ")
sqlu"insert into #$tableName(#$columns) values (#${rowData(0)}, #${rowData(1)}, #${rowData(2)}, #${rowData(3)}, #${rowData(4)});"
}
How to build the sql query such that rowData values are binded or interpolated dynamically in Slick using Scala?
def insertToTableSQLQuery(tableName: String, columnDefinitions: Seq[ColumnDefinition], rowData: ListBuffer[Any]): Future[Int] = db.run {
val columnNames = columnDefinitions.map(_.name).mkString(", ")
val placeholders = List.fill(rowData.length)("?").mkString(", ")
sqlu"insert into #$tableName(#$columnNames) values (#${rowData.map(_ => "?").mkString(", ")});".bind(rowData: _*)
}
I have tried to use parameter binding but this is throwing an error for me.
THE ERROR
value bind is not a member of slick.sql.SqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect]
[error] possible cause: maybe a semicolon is missing before `value bind`?
[error] .bind(rowData: _*)
[error]
There are two ways in slick of inject values at runtime in a plain sql.
So, for literal values such as tables or columns you will need to use
#$and$for variable values.In your case the code should be something like
This is not enough to solve the problem because when the code is compiled, you would get the following error
which means, slick doesn't know how to bind values of type
Any. Slick provides implicit SetParameter for common values such as Int, Boolean, String, Doubel, BigDecimal, etc.One way of fixing that, is to create your own
implicit SetParameter[Any] = ???. I suggest to avoid the use ofAnyas much as you can in any scala project unless you really need to.The other option is to have a
case classor aTupleinstead of aList[Any]. The case class is easier to use because you can set a name to each field mean while when you want to access the tuple you need to know the position of the value. The case class is also easier to refactor.