Java如何将光标移动到最后一条记录?
要将光标移到结果集的末尾(最后一条记录之后),可以调用afterLast()结果集的方法。
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 ScrollableAfterLastExample { 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 resultSet = statement.executeQuery(sql); //让我们跳到最后的记录。afterLast()方法将 //将光标置于最后一条记录之后。 resultSet.afterLast(); while (resultSet.previous()) { String code = resultSet.getString("code"); String name = resultSet.getString("name"); double price = resultSet.getDouble("price"); System.out.println(code + "\t" + name + "\t" + price); } } catch (SQLException e) { e.printStackTrace(); } } }
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>