我有这种方法来获取一行字符串并打印它们.
另外,我必须做两次while(Resultset.next())两次.第一个是获取行数,第二个是打印字符串.但是,当该方法第一次运行Resultset.next()时,该方法将跳过第二个Resultset.next().
public static String[] gett() throws ClassNotFoundException, SQLException{
// this for get conneced to the database .......................
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","111");
Statement st = conn.createStatement();
ResultSet re = st.executeQuery("select location_id from DEPARTMENTS");
// Ok , now i have the ResultSet ...
// the num_row it's counter to get number of rows
int num_row = 0;
// this Arrar to store String values
String[] n = new String[num_row];
// this is the first ResultSet.next , and it's work ..!
// also , this ResultSet.next work to get number on rows and store the number on 'num_row'
while(re.next())
num_row++;
// NOW , this is the secound 'ResultSet.next()' , and it's doesn't WORK !!!!
while(re.next()) {
System.out.println(re.getString("location_id"));
}
}
问题是,第一个Resultset.next()可以正常工作,但是第二个则无法工作!
有人可以解释为什么吗?我该如何运作呢?
注意:
我知道,在一个Resultset.next()中还有另一种方法可以做到这一点.
但是我想做两次;)
解决方法:
您可以将您的Statement初始化为以下内容
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
因此,您可以在Statement中移动光标.
现在您可以遍历它.
while(re.next())
num_row++;
re.beforeFirst();
但这是不必要的,最佳解决方案是跳到集合的末尾并返回行
num_row = 0;
if(re.last()) {
num_row = rs.getRow();
re.beforeFirst();
}