title: Java SQL safely check if column exists
body: <p>I need to have dynamic SQL which accepts table and column names from users and uses those in queries. Right now I do this with </p>
  
  <pre><code>public Object doSearch(String table, List&lt;String&gt; columns) {
  //... some logic
  String.format("SELECT %s from %s", String.join(", ", columns), table");
  //... some execution and return
  }
  </code></pre>
  
  <p>The source is NOT trusted, so I want to do a whitelist of table and column names, but that list changes. The list of valid tables is strictly the list of tables on <code>my_schema</code> and the list of valid columns is strictly the columns on that particular table.</p>
  
  <p>I've searched around SO and gotten a solution that looks something like:</p>
  
  <pre><code>private boolean validate(String tableName, List&lt;String&gt; columnNames) throws SQLException {
      return tableExist(tableName) &amp;&amp; columnNames.stream().allMatch(cn -&gt; columnExistsOnTable(tableName, cn));
  }
  private boolean tableExist(String tableName) throws SQLException {
      try (ResultSet rs = connection.getMetaData().getTables(null, schema, tableName, null)) {
          while (rs.next()) {
              String tName = rs.getString("TABLE_NAME");
              if (tName != null &amp;&amp; tName.equals(tableName)) {
                  return true;
              }
          }
      }
      return false;
  }
  
  private boolean columnExistsOnTable(String tableName, String columnName) {
      try (ResultSet rs = connection.getMetaData().getColumns(null, schema, tableName, columnName)) {
          while (rs.next()) {
              String tName = rs.getString("COLUMN_NAME");
              if (tName != null &amp;&amp; tName.equals(tableName)) {
                  return true;
              }
          }
      } catch (SQLException sqle) {
          return false;
      }
      return false;
  }
  </code></pre>
  
  <p>Is this safe and correct?</p>