Java如何检查光标是否在第一行?
迭代可滚动的结果集时,可以检查您是否位于结果集的开头。该isBeforFirst()方法检查位置是否在开头,如果是,则此方法将返回true,否则将返回false。
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 ScrollableIsBeforeFirstExample { 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); //使用isBeforeFirst()方法,我们可以检查是否在 //结果集的开始。 if (resultSet.isBeforeFirst()) { System.out.println("You are at the beginning of the " + "result set."); } } 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>