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 {
    String url = "jdbc:odbc:databaseName";
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String user = "guest";
    String password = "guest";

    try {/*from w  w w  . ja v a 2s.co m*/
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);

        // Get the MetaData
        DatabaseMetaData metaData = conn.getMetaData();

        // Get driver information
        System.out.println("Driver Informaion");
        System.out.println(metaData.getDriverName());
        System.out.println(metaData.getDriverVersion());
        // Get schema information
        System.out.println("Schemas");
        ResultSet schemas = metaData.getSchemas();
        while (schemas.next()) {
            System.out.println(schemas.getString(1));
        }
        // Get table information
        System.out.println("Tables");
        ResultSet tables = metaData.getTables("", "", "", null);
        while (tables.next()) {
            System.out.println(tables.getString(3));
        }
        conn.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");

    ResultSet rsColumns = null;/* w  w  w  .  ja v  a  2s  .  c  o  m*/
    DatabaseMetaData meta = conn.getMetaData();
    rsColumns = meta.getColumns(null, "%", "code", "%");

    while (rsColumns.next()) {
        String columnType = rsColumns.getString("TYPE_NAME");
        String columnName = rsColumns.getString("COLUMN_NAME");
        int size = rsColumns.getInt("COLUMN_SIZE");
        int nullable = rsColumns.getInt("NULLABLE");
        int position = rsColumns.getInt("ORDINAL_POSITION");

        System.out.println("column name=" + columnName);
        System.out.println("type=" + columnType);
        System.out.println("size=" + size);
        if (nullable == DatabaseMetaData.columnNullable) {
            System.out.println("nullable is true");
        } else {
            System.out.println("nullable is false");
        }
        System.out.println("position" + position);
    }

    conn.close();
}

From source file:com.alifi.jgenerator.spring.SpringGeneratorFactory.java

public static void main(String[] args) {
    @SuppressWarnings("unused")
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/SpringContext.xml");

    for (DataSourceMap m : DataSourceUtil.getDataSourceMap()) {

        DataSource ds = m.getDataSource();
        try {//from w w w  .  j  a v a2  s .  c o m
            Connection con = ds.getConnection();
            DatabaseMetaData dmd = con.getMetaData();
            String catalog = con.getCatalog();
            String schemaPattern = dmd.getSchemaTerm();
            System.out.println("Catalog:" + con.getCatalog() + " schemaPattern:" + schemaPattern);
            ResultSet rs = dmd.getTables(catalog, schemaPattern, "time_zone_transition", null);

            Statement s = null;
            ResultSet xrs = null;
            try {
                s = con.createStatement();
                xrs = s.executeQuery("select * from time_zone_transition");
                if (xrs.next()) {
                    p("xxxxxxxxxxxxxxxxxxxxxxxx:" + xrs.getString(1));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
            }

            while (rs.next()) {
                p("-----------------------");
                p("TABLE_CAT  :" + rs.getString("TABLE_CAT"));
                p("TABLE_SCHEM:" + rs.getString("TABLE_SCHEM"));
                p("TABLE_NAME :" + rs.getString("TABLE_NAME"));
                p("TABLE_TYPE :" + rs.getString("TABLE_TYPE"));
                p("REMARKS:   " + rs.getString("REMARKS"));

                p("11111111111111111:" + rs.getMetaData().getColumnClassName(1));
                // 
                ResultSet pkeyRs = dmd.getPrimaryKeys(catalog, schemaPattern, rs.getString("TABLE_NAME"));
                while (pkeyRs.next()) {
                    p("M-------------M");
                    p("------COLUMN_NAME:" + pkeyRs.getString("COLUMN_NAME"));
                    p("------KEY_SEQ:" + pkeyRs.getString("KEY_SEQ"));
                    p("------PK_NAME:" + pkeyRs.getString("PK_NAME"));
                }
                // 
                ResultSet rss = dmd.getColumns(catalog, schemaPattern, rs.getString("TABLE_NAME"), null);
                int cCount = rss.getMetaData().getColumnCount();
                for (int i = 1; i <= cCount; i++) {
                    p("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
                    p("       getColumnClassName:" + rss.getMetaData().getColumnClassName(i));
                    p("       getColumnLabel:" + rss.getMetaData().getColumnLabel(i));
                    p("       getColumnName:" + rss.getMetaData().getColumnName(i));
                    p("       getColumnTypeName:" + rss.getMetaData().getColumnTypeName(i));
                    p("       getColumnType:" + ColumnTypes.getType(rss.getMetaData().getColumnType(i)));
                }
            }
            rs = dmd.getTableTypes();

            while (rs.next()) {
                p("=========================");
                p("TABLE_TYPE: " + rs.getString("TABLE_TYPE"));
            }
            // ResultSetMetaData rsmd = rs.getMetaData();

            // int numberOfColumns = rsmd.getColumnCount();
            // for (int i = 1; i <= numberOfColumns; i++)
            // p(rsmd.getColumnName(i));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        p(m.toString());
    }
}

From source file:GetColumnPrivilegesOracle.java

public static void main(String[] args) throws Exception {
    Connection conn = null;

    conn = getConnection();/*from  ww  w .j  a va  2  s . c  o m*/
    String catalogPattern = conn.getCatalog();
    String schemaPattern = "SYSTEM";
    String tableNamePattern = "HELP";

    ResultSet privileges = null;
    DatabaseMetaData meta = conn.getMetaData();

    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero or more characters.
    privileges = meta.getTablePrivileges(catalogPattern, schemaPattern, tableNamePattern);
    while (privileges.next()) {

        String catalog = privileges.getString("TABLE_CAT");
        String schema = privileges.getString("TABLE_SCHEM");
        String tableName = privileges.getString("TABLE_NAME");
        String privilege = privileges.getString("PRIVILEGE");
        String grantor = privileges.getString("GRANTOR");
        String grantee = privileges.getString("GRANTEE");
        String isGrantable = privileges.getString("IS_GRANTABLE");

        System.out.println("table name:" + tableName);
        System.out.println("catalog:" + catalog);
        System.out.println("schema:" + schema);
        System.out.println("privilege:" + privilege);
        System.out.println("grantor:" + grantor);
        System.out.println("isGrantable:" + isGrantable);
        System.out.println("grantee:" + grantee);
        conn.close();

    }
}

From source file:Main.java

public static void main(String[] args) {
    long begTime = System.currentTimeMillis();

    String driver = DEFAULT_DRIVER;
    String url = DEFAULT_URL;
    String username = DEFAULT_USERNAME;
    String password = DEFAULT_PASSWORD;

    Connection connection = null;

    try {/*w  ww  .j a va  2 s . com*/
        connection = createConnection(driver, url, username, password);
        DatabaseMetaData meta = connection.getMetaData();
        System.out.println(meta.getDatabaseProductName());
        System.out.println(meta.getDatabaseProductVersion());

        String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON";
        System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));

        connection.setAutoCommit(false);
        String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
        List parameters = Arrays.asList("Foo", "Bar");
        int numRowsUpdated = update(connection, sqlUpdate, parameters);
        connection.commit();

        System.out.println("# rows inserted: " + numRowsUpdated);
        System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
    } catch (Exception e) {
        rollback(connection);
        e.printStackTrace();
    } finally {
        close(connection);
        long endTime = System.currentTimeMillis();
        System.out.println("wall time: " + (endTime - begTime) + " ms");
    }
}

From source file:JDBCMeta.java

public static void main(String[] av) {
    int i;/*from  w w  w.j  ava 2s .c o  m*/
    try {
        // Load the driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        // DriverManager.setLogStream(System.err);

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd

        // Get a Database MetaData as a way of interrogating
        // the names of the tables in this database.
        DatabaseMetaData meta = conn.getMetaData();

        System.out.println("We are using " + meta.getDatabaseProductName());
        System.out.println("Version is " + meta.getDatabaseProductVersion());

        int txisolation = meta.getDefaultTransactionIsolation();
        System.out.println("Database default transaction isolation is " + txisolation + " ("
                + transactionIsolationToString(txisolation) + ").");

        conn.close();

        System.out.println("All done!");

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException ex) {
        System.out.println("Database access failed:");
        System.out.println(ex);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    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 rs = meta.getExportedKeys(conn.getCatalog(), null, "survey");
    while (rs.next()) {
        String fkTableName = rs.getString("FKTABLE_NAME");
        String fkColumnName = rs.getString("FKCOLUMN_NAME");
        int fkSequence = rs.getInt("KEY_SEQ");
        System.out.println("getExportedKeys(): fkTableName=" + fkTableName);
        System.out.println("getExportedKeys(): fkColumnName=" + fkColumnName);
        System.out.println("getExportedKeys(): fkSequence=" + fkSequence);
    }/*from   w  ww .  ja  v a2s  . c om*/

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

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    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 rs = meta.getImportedKeys(conn.getCatalog(), null, "survey");
    while (rs.next()) {
        String fkTableName = rs.getString("FKTABLE_NAME");
        String fkColumnName = rs.getString("FKCOLUMN_NAME");
        int fkSequence = rs.getInt("KEY_SEQ");
        System.out.println("getExportedKeys(): fkTableName=" + fkTableName);
        System.out.println("getExportedKeys(): fkColumnName=" + fkColumnName);
        System.out.println("getExportedKeys(): fkSequence=" + fkSequence);
    }/*from www .  j a v  a2s  .  c  o  m*/

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

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')");

    DatabaseMetaData meta = conn.getMetaData();
    ResultSet 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);
    }//from  w ww.java  2  s  .  c  o m

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

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;/*from  w  w  w  .  j ava  2s.  c  o  m*/
    DatabaseMetaData meta = conn.getMetaData();
    rs = meta.getTableTypes();

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

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