2012-08-02 122 views
0

in java.How如何將一個sql查詢的結果保存到變量中?如何將JDBC查詢的結果保存到變量中?

 java.sql.PreparedStatement preparedStatement = null; 
     String query = "select season from seasonTable where league_name=?"; 

     preparedStatement = conn.prepareStatement(query); 

     preparedStatement.setString(1, league); 
     ResultSet rs = preparedStatement.executeQuery(); 

我需要將檢索到的季節保存到一個變量我怎麼能做到這一點?

回答

5

您可以撥打rs.next()將ResultSet的遊標移至下一行。該方法將返回一個布爾值,指示下一行是否實際上有,因此您可以使用if語句或while循環來檢索返回的第一行或全部行。

// only ever retrieve the value from the first returned row, even if there are multiple 
String season = null; 
if(rs.next()) 
    season = rs.getString(1); 

OR

// retrieve the values of all returned rows and store them in a list 
List<String> seasons = new ArrayList<String>(); 
while(rs.next()) 
    seasons.add(rs.getString(1)); 
0

您需要遍歷ResultSet,並獲取合適的列。例如

String season = null; 
while (rs.next()) { 
    season = rs.getString(column_name); // you can use column name or index 
} 

注意,你不妨在ResultSet檢查只有一個入口,和/或season被填充。在另一方面,你可能要錄製多發季節,因此:

List<String> seasons = new ArrayList<String>(); 
while (rs.next()) { 
    seasons.add(rs.getString(column_name)); 
} 

我寧願按名稱而不是指數,以獲得列。這樣你可以改變你的查詢(在某種程度上),並且解引用仍然可以工作。

Here是一些更多的例子。

+0

這將一次又一次改寫變量每個迭代。 – jddsantaella 2012-08-02 10:09:18

+2

是的。因此,我關於僅檢查* one *條目的評論。 – 2012-08-02 10:18:23

0
String season = null; 
if (rs.next()) { 
    season = rs.getString(1); 
} 

閱讀JDBC tutorial

0

縱觀javadoc,你會看到你在那裏是來自使用它們的索引或名稱ResultSet中訪問列的方法。對於要檢索的每種類型,有一種方法:getString(),getFloat()等...

0
String s; 
// Fetch each row from the result set 
     while (rs.next()) { 
      // Get the data from the row using the column index 
      s = rs.getString(1); 
        /** OR **/ 
      // Get the data from the row using the column name 
      s = rs.getString("season"); 
     } 
相關問題