wtian
wtian

Reputation: 318

Java: How to insert multiple values in a more elegant way for preparedStatment?

Below is my scala code, an insert query for Postgres which is to be passed to a PreparedStatement

val query =
        s"""
           |insert into structure_products (
           |identifier, "assetClass", "name",      "scoreType",
           |"field_1",  "field_2",    "field_3",   "field_4",
           |"field_5",  "field_6",    "field_7",   "field_8",
           |"field_9",  "field_10",   "field_11",  "field_12")
           |values (
           |?, ?, ?, ?,
           |?, ?, ?, ?,
           |?, ?, ?, ?,
           |?, ?, ?, ?)
           |""".stripMargin

then I have to do a manual set for 16 fields.

val statement = connection.prepareStatement(query)

statement.setString(1, identifier)
statement.setString(2, assetClass)
statement.setString(3, name)
...
statement.setTimestamp(15, field_11)
statement.setTimestamp(16, field_12)

So is there any other way to do this in a more elegant way? Thank you very much!

Upvotes: 0

Views: 274

Answers (2)

cchantep
cchantep

Reputation: 9168

You can have a look at Anorm, Not A ORM, but simple Scala JDBC mapper initiated by Play (I'm contributor of).

Upvotes: 1

NiGhMa
NiGhMa

Reputation: 121

I think one of the best approach in your case is to pass your fields and values to a function (as parameters) and generate your final INSERT statement within the function.

Upvotes: 1

Related Questions