简体   繁体   中英

ResultSetMetaData getting default value of column

I am Using Oracle database.

I want to get default value assign to column using Java JDBC.

But using ResultSetMetaData does not provide any method to get default value of column.

So please tell me any idea. Thanks in advance.

您可以运行此查询

Select DATA_DEFAULT from USER_TAB_COLUMNS where TABLE_NAME ='MyTable' and COLUMN_NAME = 'MyColumn'

below function Returns the default value of a column. call it on your ResultSetMetaData

public java.lang.String getDefaultValue(int columnIndex) // or columnName
                                 throws DriverException

like ResultSetMetaData.getDefaultValue(columnNameOrcolumnIndex)

There is no 'getDefaultValue' method on ResultSetMetaData in Java JDBC that I can find.
However the following query works:

SELECT COLUMN_NAME, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS
where table_name='<tablename>' and COLUMN_DEFAULT is not null

Connect to the db in question, or similarly with the db name querying master.

This answer uses DatabaseMetadata rather than ResultSetMetadata , so technically it does not answer the question posed. However, it appears more reliable than a query and still has long-term value for the community at large:

JDBC is there a way to detect if a column has a default?

Example:

Connection connection = ...;

DatabaseMetaData databaseMetaData = connection.getMetaData();
try (ResultSet resultSet = databaseMetaData.getColumns(null, null, "MyTable", "MyColumn")) {
    while (resultSet.next()) {
        String defaultValue = resultSet.getString("COLUMN_DEF");
        // Do something...
    }
}

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