Java JDBC Database Metadata getOnly1PrimaryKey(Connection conn, String tableName)

Here you can find the source of getOnly1PrimaryKey(Connection conn, String tableName)

Description

get Only Primary Key

License

Open Source License

Declaration

public static String getOnly1PrimaryKey(Connection conn, String tableName) throws SQLException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static String getOnly1PrimaryKey(Connection conn, String tableName) throws SQLException {
        ResultSet rs = null;//w ww  .j  a v a  2  s  .com

        try {
            String pkName = null;

            //get pk name
            DatabaseMetaData dbMeta = conn.getMetaData();
            rs = dbMeta.getPrimaryKeys(null, null, tableName.toUpperCase());

            if (rs.next()) {
                pkName = rs.getString("COLUMN_NAME");
            }

            return pkName;
        } finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }

    }

    public static List<String> getPrimaryKeys(Connection conn, String tableName) throws SQLException {
        ResultSet rs = null;

        try {
            List<String> pkNames = new ArrayList<String>();

            //get pk name
            DatabaseMetaData dbMeta = conn.getMetaData();
            rs = dbMeta.getPrimaryKeys(null, null, tableName.toUpperCase());

            while (rs.next()) {
                pkNames.add(rs.getString("COLUMN_NAME"));
            }

            return pkNames;
        } finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
        }

    }
}

Related

  1. getDBUsers(DatabaseMetaData metaData)
  2. getDriverSpecificSettings(Connection connection, String defaultUnionColumnValue)
  3. getForeignKeyDeferrability(int code)
  4. getJDBCMajorVersion(Connection conn)
  5. getNullableDescription(int type)
  6. getPrimaryKey(DatabaseMetaData metadata, String tableName)
  7. getPrimaryKeyColumn(DatabaseMetaData md, String TableName)
  8. getPrimaryKeyColumnNames(Connection connection, String tableName)
  9. getPrimaryKeys(Connection conn, String tableName)