我有帶回以下行的SQL語句:如何從JDBC結果得到行值的陣列設置
我想獲得一個JDBC這些值結果集的兩個對象。一個用於customerNo 1和另一個用於customer 2的客戶。我希望這兩個對象具有另一個具有對象值的相關標題的數組值。
結構最終將看起來像這樣(在JSON):
{customerNo:1,[ 「對象1」, 「對象2」, 「對象3」]},{customerNo:2,[」對象4「,」對象5「]}
我該如何用JDBC來實現?
我有帶回以下行的SQL語句:如何從JDBC結果得到行值的陣列設置
我想獲得一個JDBC這些值結果集的兩個對象。一個用於customerNo 1和另一個用於customer 2的客戶。我希望這兩個對象具有另一個具有對象值的相關標題的數組值。
結構最終將看起來像這樣(在JSON):
{customerNo:1,[ 「對象1」, 「對象2」, 「對象3」]},{customerNo:2,[」對象4「,」對象5「]}
我該如何用JDBC來實現?
您可以使用地圖以您想要的格式開始收集結果。
Map<Integer, Set<String>> customerTitles = new HashMap<Integer, Set<String>>();
while(resultSet.next()) {
Integer custId = resultSet.getInt(1);
Set<String> titles = customerTitles.containsKey(custId) ?
customerTitles.get(custId) : new HashSet<String>();
titles.add(resultSet.getString(2));
customerTitles.put(custId, titles);
}
一旦你擁有了它這種方式收集的,你可以在地圖和在圈內的集遍歷並將其轉換爲JSON
// Convert to Json array here using your JSON library
for(Integer custId : customerTitles.keySet()) {
for(String title : customerTitles.get(custId)) {
}
}
我能想到的兩種方法。
獲取CustomerNo
先用SELECT DISTINCT
查詢,並保存在一個COLLECTION
。 然後對於中的每個(使用循環)CustomerNo
執行SELECT Title from table WHERE CustomerNo = <collectionValue>
併爲每個CustomerNo
創建新的JSON Object
。
取RESULTSET
與SELECT CustomerNo, Title FROM tablename ORDER BY CustomerNo
。 在RESULTSET
的獲取代碼(在循環內部)中,將一個變量分配給您從RESULTSET
獲得的CustomerNo
並檢查下一行。如果您遇到新的CustomerNo
,則創建一個新的JSON Object
。
這是我會怎麼做了。 'Set's不能包含重複,這可能是一個問題。如果遇到麻煩,請使用列表。 –