简体   繁体   中英

JDBC Why is it returning me all available tables?

I have quite a complex bit of code so I can't show it all, but this part is very simple.

I have a SELECT * FROM myTable which returns a result set to this method which should print it, toUse is the name of the passed result set to this method:

ResultSetMetaData rsmd = (ResultSetMetaData) toUse.getMetaData();      

          System.out.println("");

          int numberOfColumns = rsmd.getColumnCount();

          for (int i = 1; i <= numberOfColumns; i++) {
            if (i > 1) System.out.print(",  ");
            String columnName = rsmd.getColumnName(i);
            System.out.print(columnName);
          }
          System.out.println("");

          while (toUse.next()) {
            for (int i = 1; i <= numberOfColumns; i++) {
              if (i > 1) System.out.print(",  ");
              String columnValue = toUse.getString(i);
              System.out.print(columnValue);
            }
            System.out.println("");
          }

Rather than printing out the table I selected from, it is instead excuting a SHOW TABLES; command?

Edit:

I think it has something to do with this running earlier on:

java.sql.DatabaseMetaData meta = con.getMetaData();
        results = meta.getTables(null, null, null, new String[]{"TABLE"});

        while (results.next()) {

          String tableName = results.getString("TABLE_NAME");
          if(tableName.equals(parameters)){
              return true;
          }

        }
    results.close();
    return false;

Unless you've somehow got a broken jdbc driver, there should be no problem between calling .getMetaData() on a Connection before calling .getMetaData() on a ResultSet. You've most likely accidentally altered the value of toUse. One way to validate that you haven't accidentally changed its value is to make your local variable final.

PS Instead of this:

for (int i = 1; i <= numberOfColumns; i++) {
    if (i > 1) System.out.print(",  ");
    String columnValue = toUse.getString(i);
    System.out.print(columnValue);
}

Do this:

String delimiter = "";
for (int i = 1; i <= numberOfColumns; i++) {
    String columnValue = toUse.getString(i);
    System.out.print(delimiter);
    System.out.print(columnValue);
    delimiter = ",  ";
}

No need for a branch condition inside of your loop.

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