[英]How to save the result from JDBC query into a variable?
在java中。如何将sql查询的结果保存到变量中?
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);
要么
// 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));
}
我希望按名称而不是按索引获取列。 这样,您可以(在某种程度上)更改查询,并且取消引用仍将起作用。
这里还有更多示例。
String season = null;
if (rs.next()) {
season = rs.getString(1);
}
阅读JDBC教程
查看javadoc,您会发现有一些方法可以使用ResultSet的索引或名称访问ResultSet中的列。 对于每种要检索的类型,都有一个方法: getString()
, getFloat()
等。
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.