Getting JDBC Column Types

I need to ask about my jdbc type column in a table, today I loop my columns and then ask about its type, see my code below:

public int getColumnDataTypeFromDB(String columnName) { int datatype = 0; ResultSet columns = null; try { String schema = getMetaDataCatalogName() != null ? getMetaDataCatalogName() : getMetaDataSchemaName(); if (TableManagerFactory.isCatalogBasedDatabase()) { columns = getMetaData().getColumns( schema, null, tableName, columnName); } else { columns = getMetaData().getColumns( null, schema, tableName, columnName); } // columns = // getMetaData().getColumns(getMetaDataCatalogName(), getMetaDataSchemaName(), tableName, columnName); if (columns.next()) { datatype = columns.getInt("DATA_TYPE"); } } catch (SQLException ex) { Log.error( this, "Error while getting columns information: " + ex.getMessage(), ex); //return false; } catch (DDLCreationException ex) { Log.error(this, ex.getMessage()); } finally { try { if (columns != null) { columns.close(); } } catch (SQLException ex) { Log.error(this, ex.getLocalizedMessage()); } } return datatype; } 

Can I get all the metadata of columns in such a table at the same time? if so, how can i do this?

+4
source share
3 answers

DatabaseMetaData.getColumns(..) parameters must be LIKE -pattern. Therefore, if you want to get all the columns from a table, you just need to pass "%" last parameter, columnNamePattern :

 getMetaData().getColumns(null, schema, tableName, "%"); 

Some drivers (also) allow null here, but not all drivers do this (the JDBC specification and API documentation are not entirely clear if this parameter is allowed or not)

+1
source

Use the jdbc ResultSetMetaData class to get detailed information about table columns.

  ResultSet res=stmt.executeQuery("select * from tableName where 1<0"); ResultSetMetaData rsmd=res.getMetaData(); rsmd.getColumnType(1); rsmd.getColumnLabel(1); rsmd.getColumnDisplaySize(1); 
+15
source

It seems you are looking for a column data type and then getColumnTypeName will be

  System.out.println(rsMaster.getMetaData().getColumnName(1)); System.out.println(rsMaster.getMetaData().getColumnType(1)); System.out.println(rsMaster.getMetaData().getColumnTypeName(1)); System.out.println(rsMaster.getMetaData().getColumnDisplaySize(1)); System.out.println(rsMaster.getMetaData().getColumnLabel(1)); 
0
source

Source: https://habr.com/ru/post/1495174/


All Articles