Java JDBC Database Metadata sequenceExists(String seqName, Connection conn)

Here you can find the source of sequenceExists(String seqName, Connection conn)

Description

sequence Exists

License

Open Source License

Declaration

public static boolean sequenceExists(String seqName, Connection conn) 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;

public class Main {
    public static boolean sequenceExists(String seqName, Connection conn) throws SQLException {
        DatabaseMetaData dbmd = conn.getMetaData();
        if (dbmd.getURL().startsWith("jdbc:postgresql:")) {
            return returnsAnyRows(
                    "SELECT * from pg_class where relname = '" + seqName.toLowerCase() + "' AND relkind = 'S'",
                    conn);/*from  w  w w . j av a2 s .c o  m*/
        } else if (dbmd.getURL().startsWith("jdbc:hsqldb:")) {
            // try select from system_sequences
            String whereClause = "WHERE sequence_name = '" + seqName.toUpperCase() + "'";
            try {
                return returnsAnyRows("SELECT sequence_name FROM system_sequences " + whereClause, conn);
            } catch (SQLException e) {
                // Try again as this may be a table not found exception.
                // Under HSQLDB 1.8 and later the system_sequences table
                // belongs to a schema
                return returnsAnyRows(
                        "SELECT sequence_name FROM information_schema.system_sequences " + whereClause, conn);
            }
        }
        // not postgres, so try asking as a table, maybe this works for other
        // databases
        return tableExists(seqName, conn);
    }

    private static boolean returnsAnyRows(String stmt, Connection conn) throws SQLException {
        return conn.createStatement().executeQuery(stmt).next();
    }

    public static boolean tableExists(String tableName, Connection conn) throws SQLException {
        DatabaseMetaData dbmd = conn.getMetaData();
        ResultSet rs = dbmd.getTables(null, null, null, null);
        while (rs.next()) {
            if (rs.getString("TABLE_NAME").equalsIgnoreCase(tableName)) {
                return true;
            }
        }
        return false;
    }
}

Related

  1. isSybase(DatabaseMetaData metadata)
  2. isSybaseDb(DatabaseMetaData metaData)
  3. printExistingTables(Connection conn)
  4. printMetaData(Connection con)
  5. printTableExistence(String name, Connection conn)
  6. tableExists(Connection con, String table)
  7. tableExists(Connection connection, String tableName)
  8. tableExists(Connection connection, String tableName)
  9. tableExists(DatabaseMetaData metaData, String tableName)