Home > Mobile >  how to get what are the unique columns from given table in java jdbc driver
how to get what are the unique columns from given table in java jdbc driver

Time:12-18

let say i have table called "person" and it has 4 columns(name,last_name,city,pincode) out of them 2 columns (name,last_name) are unique columns . And i want to get these 2 columns information from java jdbc driver. and my question is how get this information from java jdbc driver

CodePudding user response:

Here you have a simple example based on MySql:

public class Test {
static final String DB_URL = "jdbc:mysql://localhost:3306/yourDatabase";
static final String USER = "----";
static final String PASS = "somePass";
static final String QUERY = "SHOW KEYS FROM YOUR_TABLE WHERE Key_name = 'PRIMARY'\n";

public static void main(String[] args) {
    // Open a connection
    final ArrayList<String> primaryKeyColumns = new ArrayList<>();
    try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(QUERY);) {
        while (rs.next()) {
            primaryKeyColumns.add(rs.getString(5));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    System.out.println(primaryKeyColumns);
}

}

Look at the used query in this way you can fetch more specific information.

CodePudding user response:

This document describes the ResultSet and lays out that you can obtain a ResultSetMetaData object. But documentation of ResultSetMetaData shows that there is no way to retriev information about column constraints.

  • Related