Search code examples
springjdbcjooq

How to check if a table column exists using JdbcTemplate?


I'm trying to write a query to check if a column exists within this table. As far as I can see, I can only query rows of columns. I'm wondering if there is a way to query if a column within a table exists?

String currentTable = "";
final Query query = dslContext
        .select(field(COLUMN_COUNTRY_CODE))
        .from(MANAGEMENT_TABLE_NAME)
        .orderBy(field(COLUMN_CREATE_DATE).desc())
        .limit(inline(1));
currentTable = jdbcTemplate.queryForObject(query.getSQL(), String.class);

This is what my query looks like at the moment. I want to check if COLUMN_COUNTRY_CODE column table exists in MANAGEMENT_TABLE_NAME. How would I go about doing this?


Solution

  • With JDBC, you can achieve this by creating an instance of DatabaseMetaData like so:

    DatabaseMetaData databaseMetaData = connection.getMetaData();
    

    Where your Connection object is an instance of JdbcConnection.

    Next, by using the getColumns() method you can iterate over the columns of a particular table and check their names.

    Code sample:

        ResultSet columns = databaseMetaData.getColumns(null,null, "TABLE_NAME", null);
    while(columns.next()) {
        String columnName = columns.getString("COLUMN_NAME");    
    }
    

    Source