Java如何知道光标的当前位置?
在结果集中移动时,您可能想知道当前光标位于哪一行。要获取此信息,可以调用ResultSet的getRow()方法。
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 ScrollableGetRowExample { 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); while (resultSet.next()) { String code = resultSet.getString("code"); //通过调用结果集的getRow()方法,我们 //知道结果集中的当前行是什么 //我们正在从中读取数据。 int row = resultSet.getRow(); System.out.println(row + ". " + code); } } catch (SQLException e) { e.printStackTrace(); } } }
上面的代码片段的结果:
1. P0000001 2. P0000002 3. P0000003 4. P0000004 5. P0000005
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>