Reputation: 511
I am using spring Jdbc , How do i retrieve the database vendor name from the jdbc template without going via the Connection interface . Is there an API provided by Spring which could give an enum holding the DB name so that i can decouple my code from hardcoding a string value
Upvotes: 6
Views: 9854
Reputation: 976
The easiest way would be to use JdbcUtils#extractDatabaseMetaData
method - http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/JdbcUtils.html#extractDatabaseMetaData-javax.sql.DataSource-java.lang.String-
Like:
JdbcUtils.extractDatabaseMetaData(jdbcTemplate.getDataSource(), "getDatabaseProductName");
There is also a JdbcUtils#commonDatabaseName
method that attempts to normalize the database product names - http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/support/JdbcUtils.html#commonDatabaseName-java.lang.String-
Upvotes: 3
Reputation: 560
You could use something like this to obtain an underlying connection and then release it once you get information you need from database metadata.
DataSource dataSource = jdbcTemplate.getDataSource();
Connection connection = DataSourceUtils.getConnection(dataSource);
String dbProductName = connection.getMetaData().getDatabaseProductName();
DataSourceUtils.releaseConnection(connection, dataSource);
Hope this helps you. !
Upvotes: 2
Reputation: 178
You could find the information you need into DatabaseMetaData documentation.
String vendor = jdbcTemplate.getDataSource().getConnection().getMetaData().getDatabaseProductName();
UPDATED!
As recommended by M. Deinum, you could use a ConnectionCallback so you won't need to close the connection or take care of it.
For example:
private String getProduct() {
return this.jdbcTemplate.execute(new ConnectionCallback<String>() {
@Override
public String doInConnection(Connection connection) throws SQLException,
DataAccessException {
return connection.getMetaData().getDatabaseProductName();
}
});
}
Upvotes: 7