Example usage for java.sql Connection getMetaData

List of usage examples for java.sql Connection getMetaData

Introduction

In this page you can find the example usage for java.sql Connection getMetaData.

Prototype

DatabaseMetaData getMetaData() throws SQLException;

Source Link

Document

Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;//  www  .j  ava 2  s  . co m
    DatabaseMetaData meta = conn.getMetaData();
    rs = meta.getTables(null, null, null, new String[] { "TABLE" });

    while (rs.next()) {
        String tableName = rs.getString("TABLE_NAME");
        System.out.println("tableName=" + tableName);
    }

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    DatabaseMetaData meta = conn.getMetaData();
    String sqlKeywords = meta.getSQLKeywords();
    System.out.println(sqlKeywords);

    st.close();/*from   w  w  w. j  av a  2s  .c o  m*/
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    DatabaseMetaData meta = conn.getMetaData();
    ResultSet schemas = meta.getSchemas();
    while (schemas.next()) {
        String tableSchema = schemas.getString(1); // "TABLE_SCHEM"
        String tableCatalog = schemas.getString(2); //"TABLE_CATALOG"
        System.out.println("tableSchema" + tableSchema);
    }/*from  w ww .j a v  a2 s .  c o m*/

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] argv) {
    Connection connection = null;
    Statement statement;/* ww w . ja  v a 2 s  . c  o  m*/
    ResultSet rs;
    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/AccountsDB");
        connection = ds.getConnection();

        DatabaseMetaData md = connection.getMetaData();
        statement = connection.createStatement();

        System.out.println("getURL() - " + md.getURL());
        System.out.println("getUserName() - " + md.getUserName());
        System.out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion());
        System.out.println("getDriverMajorVersion - " + md.getDriverMajorVersion());
        System.out.println("getDriverMinorVersion - " + md.getDriverMinorVersion());
        System.out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh());

        System.out.println("<H1>Feature Support</H1>");
        System.out.println(
                "supportsAlterTableWithDropColumn - " + md.supportsAlterTableWithDropColumn() + "<BR>");
        System.out.println("supportsBatchUpdates - " + md.supportsBatchUpdates());
        System.out.println("supportsTableCorrelationNames - " + md.supportsTableCorrelationNames());
        System.out.println("supportsPositionedDelete - " + md.supportsPositionedDelete());
        System.out.println("supportsFullOuterJoins - " + md.supportsFullOuterJoins());
        System.out.println("supportsStoredProcedures - " + md.supportsStoredProcedures());
        System.out.println("supportsMixedCaseQuotedIdentifiers - " + md.supportsMixedCaseQuotedIdentifiers());
        System.out.println("supportsANSI92EntryLevelSQL - " + md.supportsANSI92EntryLevelSQL());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());
        System.out.println("getMaxRowSize - " + md.getMaxRowSize());
        System.out.println("getMaxStatementLength - " + md.getMaxStatementLength());
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxConnections - " + md.getMaxConnections());
        System.out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength());

        System.out.println("getTableTypes()");
        rs = md.getTableTypes();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
        System.out.println("getTables()");
        rs = md.getTables("accounts", "", "%", new String[0]);
        while (rs.next()) {
            System.out.println(rs.getString("TABLE_NAME"));
        }
        System.out.println("Transaction Support");
        System.out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation());
        System.out
                .println("dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions());

        System.out.println("General Source Information");
        System.out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect());
        System.out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable());
        System.out.println("getTimeDateFunctions - " + md.getTimeDateFunctions());
        System.out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar());

        System.out.println("getTypeInfo()");
        rs = md.getTypeInfo();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar, PRIMARY KEY (id) );");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;/*w  ww  .ja v  a2 s  .  c  om*/
    DatabaseMetaData meta = conn.getMetaData();
    // The Oracle database stores its table names as Upper-Case,
    // if you pass a table name in lowercase characters, it will not work.
    // MySQL database does not care if table name is uppercase/lowercase.
    //
    rs = meta.getPrimaryKeys(null, null, "survey");

    java.util.List list = new java.util.ArrayList();
    while (rs.next()) {
        String columnName = rs.getString("COLUMN_NAME");
        System.out.println("getPrimaryKeys(): columnName=" + columnName);
    }

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    DatabaseMetaData meta = conn.getMetaData();

    if (meta.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY)) {
        System.out.println("type name=TYPE_FORWARD_ONLY");
    }//from w ww. j  a v  a  2  s .  co  m
    if (meta.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)) {
        System.out.println("type name=TYPE_SCROLL_INSENSITIVE");
    }
    if (meta.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)) {
        System.out.println("type name=TYPE_SCROLL_SENSITIVE");
    }

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;//from   w  w  w. j a  v  a2  s.  c  o m
    DatabaseMetaData meta = conn.getMetaData();
    System.out.println(meta.getDriverVersion());

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;/* ww  w . j a  v  a2  s.c o m*/
    DatabaseMetaData meta = conn.getMetaData();
    System.out.println(meta.getDriverName());

    st.close();
    conn.close();
}

From source file:net.ontopia.topicmaps.cmdlineutils.rdbms.RDBMSIndexTool.java

public static void main(String[] argv) throws Exception {

    // Initialize logging
    CmdlineUtils.initializeLogging();/*from   w  w w  . j a va  2  s  .c o  m*/

    // Register logging options
    CmdlineOptions options = new CmdlineOptions("RDBMSIndexTool", argv);
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();

    if (args.length != 1) {
        usage();
        System.exit(3);
    }

    // load database schema project
    ClassLoader cloader = RDBMSIndexTool.class.getClassLoader();
    InputStream istream = cloader.getResourceAsStream("net/ontopia/topicmaps/impl/rdbms/config/schema.xml");
    Project dbp = DatabaseProjectReader.loadProject(istream);

    // open database connection
    String propfile = args[0];
    ConnectionFactoryIF cf = new DefaultConnectionFactory(PropertyUtils.loadProperties(new File(propfile)),
            true);

    Connection conn = cf.requestConnection();
    try {
        DatabaseMetaData dbm = conn.getMetaData();
        boolean downcase = dbm.storesLowerCaseIdentifiers();

        Map extra_indexes = new TreeMap();
        Map missing_indexes = new TreeMap();

        Iterator tables = dbp.getTables().iterator();
        while (tables.hasNext()) {
            Table table = (Table) tables.next();
            String table_name = (downcase ? table.getName().toLowerCase() : table.getName());
            //! System.out.println("T :"  + table_name);

            // get primary keys from database
            Map pkeys = getPrimaryKeys(table_name, dbm);

            // get indexes from database
            Map indexes = getIndexes(table_name, dbm);

            Map dindexes = new HashMap();
            if (table.getPrimaryKeys() != null) {
                String pkey = table_name + '(' + StringUtils.join(table.getPrimaryKeys(), ',') + ')';
                if (!pkeys.containsKey(pkey))
                    System.out.println("PKM: " + pkey);
            }

            Iterator iter = table.getIndexes().iterator();
            while (iter.hasNext()) {
                Index index = (Index) iter.next();
                String i = table_name + '(' + StringUtils.join(index.getColumns(), ',') + ')';
                String index_name = (downcase ? index.getName().toLowerCase() : index.getName());
                dindexes.put(i, index_name);
            }

            Set extra = new HashSet(indexes.keySet());
            extra.removeAll(dindexes.keySet());
            extra.removeAll(pkeys.keySet());
            if (!extra.isEmpty()) {
                Iterator i = extra.iterator();
                while (i.hasNext()) {
                    Object k = i.next();
                    extra_indexes.put(k, indexes.get(k));
                }
            }

            Set missing = new HashSet(dindexes.keySet());
            missing.addAll(pkeys.keySet());
            missing.removeAll(indexes.keySet());
            if (!missing.isEmpty()) {
                Iterator i = missing.iterator();
                while (i.hasNext()) {
                    Object k = i.next();
                    missing_indexes.put(k, dindexes.get(k));
                }
            }

        }
        if (!extra_indexes.isEmpty())
            System.out.println("/* --- Extra indexes ----------------------------------------- */");
        Iterator eiter = extra_indexes.keySet().iterator();
        while (eiter.hasNext()) {
            Object k = eiter.next();
            System.out.println("drop index " + extra_indexes.get(k) + "; /* " + k + " */");
        }

        if (!missing_indexes.isEmpty())
            System.out.println("/* --- Missing indexes---------------------------------------- */");
        Iterator miter = missing_indexes.keySet().iterator();
        while (miter.hasNext()) {
            Object k = miter.next();
            System.out.println("create index " + missing_indexes.get(k) + " on " + k + ";");
        }

    } finally {
        conn.rollback();
        conn.close();
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    DatabaseMetaData meta = conn.getMetaData();
    // Oracle (and some other vendors) do not support
    // some the following methods; therefore, we need
    // to use try-catch block.
    try {/*from w w  w .jav a 2  s .  c  o  m*/
        int jdbcMajorVersion = meta.getJDBCMajorVersion();
        System.out.println("jdbcMajorVersion:" + jdbcMajorVersion);
    } catch (Exception e) {
        System.out.println("jdbcMajorVersion unsupported feature");
    }

    try {
        int jdbcMinorVersion = meta.getJDBCMinorVersion();
        System.out.println("jdbcMinorVersion:" + jdbcMinorVersion);
    } catch (Exception e) {
        System.out.println("jdbcMinorVersion unsupported feature");
    }

    String driverName = meta.getDriverName();
    String driverVersion = meta.getDriverVersion();
    System.out.println("driverName=" + driverName);
    System.out.println("driverVersion=" + driverVersion);

    st.close();
    conn.close();
}