如何将JDBC查询的结果保存到变量中?
问题描述:
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();
我需要将检索到的季节保存到一个变量我怎么能做到这一点?
答
您可以拨打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));
答
您需要遍历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是一些更多的例子。
答
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");
}
这将一次又一次改写变量每个迭代。 – jddsantaella 2012-08-02 10:09:18
是的。因此,我关于仅检查* one *条目的评论。 – 2012-08-02 10:18:23