The ResultSetMetaData.isAutoIncrement()
method can tell us if a column value is automatically numbered or not. This method return true
when the column is an auto-increment column, otherwise it returns false
. See the example below where we check if the first column (id
) is an auto-increment column.
package org.kodejava.jdbc;
import java.sql.*;
public class IsAutoIncrementExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
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 resultSet = statement.executeQuery(
"SELECT id, username, order_date FROM purchase_order");
// The ResultSetMetaData is where all metadata related
// information for a result set is stored.
ResultSetMetaData metadata = resultSet.getMetaData();
if (metadata.isAutoIncrement(1)) {
System.out.println("Column `id` is an auto-increment column.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Maven dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023