Java代码获取当前连接的数据库类型,这里使用org.springframework.jdbc.core.JdbcTemplate
类。
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
代码:
private String checkDbType() {
try {
String jdbcConnectInfo = jdbcTemplate.getDataSource().getConnection().getMetaData().getDriverName().toUpperCase();
if (jdbcConnectInfo.indexOf("MYSQL") != -1) {
return "MYSQL";
} else if (jdbcConnectInfo.indexOf("SQL SERVER") != -1) {
return "SQLSERVER";
} else if (jdbcConnectInfo.indexOf("ORACLE") != -1) {
return "ORACLE";
}
return jdbcConnectInfo;
} catch (SQLException throwables) {
throwables.printStackTrace();
return "UNKOWN";
}
}