Java如何移至绝对行或相对行?
在此示例中,我们向您展示如何使用结果集absolute()和relative()方法从一个结果集行跳转到另一行。当您传递正数作为参数时,您将从第一条记录移至最后一条记录。但是,如果您传递负数作为参数,则会从最后一条记录向后移动。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MoveAbsoluteOrRelativeExample { private static final String URL = "jdbc:mysql://localhost/nhooo"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql = "SELECT code, name, price FROM products"; ResultSet rs = statement.executeQuery(sql); //移至第二行 rs.absolute(2); System.out.println("You are now in: " + rs.getRow()); //从当前位置向前移动2条记录 //(第四行) rs.relative(2); System.out.println("You are now in: " + rs.getRow()); //移至结果集中的最后一行 rs.absolute(-1); System.out.println("You are now in: " + rs.getRow()); //从当前位置向后移动3条记录 //(第二行) rs.relative(-3); System.out.println("You are now in: " + rs.getRow()); } catch (SQLException e) { e.printStackTrace(); } } }
该代码输出以下结果:
You are now in: 2 You are now in: 4 You are now in: 5 You are now in: 2
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency>