简体   繁体   中英

Java JDBC get tables

I have a method which displays tables in a JCombo Box.

private void getTables() throws SQLException {


    dburl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    connection = DriverManager.getConnection(dburl, "c##lambros", "16111111");
    dbmd = connection.getMetaData();
    rset= dbmd.getTables(null, null, "%", null);

    while (rset.next()) {
      System.out.println(rset.getString(3));
    }

}

The problem is that I have ONLY 3 tables called: Criminals, Agents, Informants, but the method returns me all kinds of tables like: _GV$SXGG_APPLY_READER, _GV$SXGG_APPLY_SERVER, _GV$SXGG_CAPTURE for example and hundreds of others. How do I filter them out?

I found it. The proper code is:

private void getTables() throws SQLException {


    dburl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    connection = DriverManager.getConnection(dburl, "c##lambros", "16111111");
    dbmd = connection.getMetaData();
    query = " Select table_name FROM user_tables ";
    stmt = connection.createStatement();
    rset = stmt.executeQuery(query);

    while (rset.next()) {
      System.out.println(rset.getString(1));
    }

}

Here is some doc suggests using stmt.executeQuery("select object_name from user_objects where object_type = 'TABLE'") like this:

public static void main(String[] args) throws Exception {
    Connection conn = getOracleConnection();
    Statement stmt = null;
    ResultSet rs = null;
    stmt = conn.createStatement();
    //only for Oracle
    rs = stmt.executeQuery("select object_name from user_objects where object_type = 'TABLE'");

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

    stmt.close();
    conn.close();
  }

This will work for Oracle only though

As per the oracle docs getTables() accepts 4 arguments like catalog, schemaPattern,tableNamePattern,types but you are making null so you are getting all the table names

in your existing code make the 4th arguement this way new String[]{"TABLE"}

full code will be

private void getTables() throws SQLException {

String[] types = {"TABLE"};
    dburl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    connection = DriverManager.getConnection(dburl, "c##lambros", "16111111");
    dbmd = connection.getMetaData();
    rset= dbmd.getTables(null, null, "%", types);

    while (rset.next()) {
      System.out.println(rset.getString("TABLE_NAME"));
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM