Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java.util.List<String> into java.sql.Array

Tags:

java

jdbc

How would you convert a java.util.List<String> instance into a java.sql.Array?

like image 440
John Jesudason D Avatar asked May 21 '10 07:05

John Jesudason D


People also ask

Can list converted to array?

Create a List object. Add elements to it. Create an empty array with size of the created ArrayList. Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.

Can you convert an ArrayList to an array?

To convert ArrayList to array in Java, we can use the toArray(T[] a) method of the ArrayList class. It will return an array containing all of the elements in this list in the proper order (from first to last element.) Here's a short example to convert an ArrayList of integers, numbersList , to int array.

Can we convert string array to list?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.


1 Answers

Use connection.createArrayOf(...)

For example:

final String[] data = yourList.toArray(new String[yourList.size()]); final java.sql.Array sqlArray = connection.createArrayOf(typeName, data); statement.setArray(position, sqlArray); 

Where typeName is:

the SQL name of the type the elements of the array map to. The typeName is a database-specific name which may be the name of a built-in type, a user-defined type or a standard SQL type supported by this database. This is the value returned by Array.getBaseTypeName


As noted in the comments, this is Java 1.6. For older versions you can't create this in a driver-independent way. You are only supposed to get arrays, not create them. If you want to, you can instantiate the implementing class from your jdbc driver, but this is non-portable.

like image 147
Bozho Avatar answered Oct 05 '22 05:10

Bozho