Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding parameter as PostgreSQL array

I'm trying to bind a prepared statement parameter which is a "multidimensional" PostgreSQL array. Here's an array example (column type is numeric[]):

{{1,10},{2,20}}

How do I bind a value like that using a prepared statement? I tried:

stmt.setObject(1, "{{1,10},{2,20}}", Types.ARRAY);

It didn't work:

Cannot cast an instance of java.lang.String to type Types.ARRAY

Any ideas?

like image 389
Ree Avatar asked Sep 06 '13 12:09

Ree


People also ask

How do I declare an array variable in PostgreSQL?

PostgreSQL Array type PL/pgSQL in PostgreSQL allows us to declare a variable as an ARRAY type. This ARRAY can be either a base or a custom type. For example, if we want to store a list of PINCODE values, then, we can declare the variable as v_pincode INT[].

How do I declare a string array in PostgreSQL?

Syntax. In the above syntax, we can declare a String Array data type at the time of table creation. Where table name is the specified table name that we need to create and column 1, column 2, and column n declared with the data type of array and it separated by using a comma.

How do I bind variables in PostgreSQL?

In PostgreSQL, bind variables are numbers preceeded by a $ sign. When using SQL Relay bind functions, to refer to an Oracle, Sybase or MS SQL Server bind variable, you should use its name without the preceeding colon.


1 Answers

Try something like this (untested):

                ------------------ your connection
                V
Array inArray = conn.createArrayOf("integer", new Integer[][] {{1,10},{2,20}});
stmt.setArray(1, inArray);

Links:

  • Postgres and multi-dimensions arrays in JDBC
  • Passing Array from Java to Postgres
like image 67
Roman Pekar Avatar answered Sep 20 '22 15:09

Roman Pekar