2012-08-02 124 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"); 
     } 
相关问题