Somaiah Kumbera
Somaiah Kumbera

Reputation: 7539

How to perform a multi row insert in postgres with a prepared statement

I'm trying to use the multi row insert with postgres

INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2),
...
(value_list_n);

on a list of Strings that can of course be of variable length.

How can I use this with a prepared statement?

Upvotes: 1

Views: 41

Answers (1)

Somaiah Kumbera
Somaiah Kumbera

Reputation: 7539

The answer is with Postgres unnest. This is postgres proprietary so it unfortunately won't work with all SQL:

val ssnList: List<String> = listOf("1", "2")

conn.prepareStatement("insert into ssns values (unnest(?))").use { stm ->
    val array = conn.createArrayOf("VARCHAR", ssnList.toTypedArray())
    stm.setArray(1, array)
    stm.execute()
}

Upvotes: 4

Related Questions