Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Result Set from SQL Array to Array of Strings

I am querying the information_schema.columns table in my PostgreSQL database. Using a table name, the result set finds all the column names, type, and whether it is nullable (except for the primary key, 'id'). This is the query being used:

SELECT column_name, is_nullable,data_type FROM information_schema.columns WHERE lower(table_name) = lower('TABLE1') AND column_name != 'id' ORDER BY ordinal_position; 

I have a string array for each of these results and I am trying to use the ResultSet method getArray(String columnLabel) to avoid looping through the results. I want to store the returned Arrays in the string arrays, but get a type mismatch error

Type mismatch: cannot convert from Array to String[] 

Is there a way to convert or typecast the SQL Array object to a String[]?

Relevant Code:

String[] columnName, type, nullable;  //Get Field Names, Type, & Nullability  String query = "SELECT column_name, is_nullable,data_type FROM information_schema.columns "         + "WHERE lower(table_name) = lower('"+tableName+"') AND column_name != 'id' "         + "ORDER BY ordinal_position";  try{     ResultSet rs = Query.executeQueryWithRS(c, query);     columnName = rs.getArray(rs.getArray("column_name"));     type = rs.getArray("data_type");     nullable = rs.getArray("is_nullable"); }catch (Exception e) {     e.printStackTrace(); } 
like image 799
Matt Avatar asked Feb 18 '13 11:02

Matt


People also ask

Can a Set be converted to array?

Add elements to it. Create an empty array with size of the created Set. Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it. Print the contents of the array.

How do you store results Set values in an array?

Use ArrayList (or any other Collection type you prefer) instead of Array. For array you would have to run extra query determinate number of elements that will come out to give you array size. That you would have to initialize array with that size and only after that you could … Do NOT use scriptlets in JSP.


2 Answers

Use:

Array a = rs.getArray("is_nullable"); String[] nullable = (String[])a.getArray(); 

As explained here

Array is SQL type, getArray() returns an object to cast to java array.

like image 88
BobTheBuilder Avatar answered Sep 20 '22 18:09

BobTheBuilder


Generalize the Array to Object

    Object[] type; //this is generic can use String[] directly     Array rsArray;      rsArray = rs.getArray("data_type");     type = (Object [])rsArray.getArray(); 

Use it loop as string:

type[i].toString(); 
like image 27
TheWhiteRabbit Avatar answered Sep 17 '22 18:09

TheWhiteRabbit