2013-02-18 138 views
17

我正在查詢PostgreSQL數據庫中的information_schema.columns表。使用表名稱,結果集會查找所有列名稱,類型以及是否爲空(除了主鍵'id')。這是正在使用的查詢:將結果集從SQL數組轉換爲字符串數組

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; 

我對這些結果的字符串數組,我試圖用的ResultSet方法getArray(String columnLabel),以避免通過結果循環。我想返回數組存儲在字符串數組,卻得到了一個類型不匹配錯誤

Type mismatch: cannot convert from Array to String[] 

有沒有辦法到SQL Array對象轉換或強制轉換爲String []?

相關代碼:

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(); 
} 

回答

30

用途:

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

如所解釋的here

Array是SQL類型,getArray()返回一個對象投射到Java數組。

+1

謝謝,我嘗試過使用'rs.getArray(「is_nullable」)。getArray()',但我認爲我沒有對它進行類型轉換。這似乎解決了我的問題。 – Matt 2013-02-18 11:36:49

3

概括陣列到對象

Object[] type; //this is generic can use String[] directly 
    Array rsArray; 

    rsArray = rs.getArray("data_type"); 
    type = (Object [])rsArray.getArray(); 

使用它環路字符串:

type[i].toString(); 
+0

這仍然會導致錯誤。 「_Type不匹配:無法從數組轉換爲對象[] _」。我認爲主要的問題是ResultSet'getArray'方法返回[java.sql數組](http://docs.oracle.com/javase/7/docs/api/java/sql/Array.html),而不是java.lang Object類下的java.util.Arrays類型。 這是關於我的方法的[javadoc](http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getArray(java.lang.String))使用。 – Matt 2013-02-18 11:30:47

+0

@Matt編輯和驗證,getArray()將返回Array,Array.getArray()返回java數組。 – TheWhiteRabbit 2013-02-18 11:40:40

+0

正確,現在可以工作,但它需要不必要地使用'toString()'。在ResultSet中包含未知或各種對象的情況下,推廣到Object []可能會更有用。在我的情況下,我只需要字符串。 – Matt 2013-02-18 11:45:27

0

如何設置從SQL數組的ArrayList屬性:

Array a = rs.getArray("col"); // smallint[] column 
if (a != null) { 
    yourObject.setListProperty(Arrays.asList((Integer[]) a.getArray())); 
} 
+0

第3行的這個「o」是什麼? – DerMike 2017-03-16 15:27:48

+1

o是具有屬性listProperty的對象的一個​​實例List yglodt 2017-03-16 16:00:32