Java SQL Key getForeignKeys(String toTable, Connection con, boolean force)

Here you can find the source of getForeignKeys(String toTable, Connection con, boolean force)

Description

get Foreign Keys

License

Apache License

Declaration

public static List<String> getForeignKeys(String toTable, Connection con, boolean force) throws SQLException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import java.util.List;

public class Main {
    public static List<String> getForeignKeys(String toTable, Connection con, boolean force) throws SQLException {
        toTable = normalizeTableName(toTable, con);
        ResultSet rs = con.getMetaData().getExportedKeys(null, null, toTable);
        List<String> sqls = new ArrayList<>(2);
        while (rs.next()) {
            String tablename = rs.getString("FKTABLE_NAME");
            String fkname = rs.getString("FK_NAME");
            if (fkname != null) {
                sqls.add("alter table " + tablename + " drop constraint " + fkname);
            }/*from   w w w.j a v a 2  s  . c  om*/
        }
        rs.close();
        return sqls;

    }

    public static String normalizeTableName(String table, Connection con) throws SQLException {
        for (String t : getTables(con)) {
            if (t.equalsIgnoreCase(table)) {
                return t;
            }
        }
        return table;
    }

    public static List<String> getTables(Connection con) throws SQLException {
        String[] types = { "TABLE" };
        ResultSet rs = con.getMetaData().getTables(null, null, "%", types);
        List<String> tables = new ArrayList<String>();
        while (rs.next()) {
            tables.add(rs.getString("TABLE_NAME"));
        }
        rs.close();
        return tables;

    }
}

Related

  1. getData(String key)
  2. isKeyAnInteger(Connection dbConn)