jdbc, jdbcTemplate get database type

In many cases, the system needs to connect to multiple databases for processing, or consider the issue of code compatibility with different databases. Of course, using hibernate does not need to consider these problems, but if you want to use only jdbc, you must consider this problem, because different databases use different SQL syntax.
How to determine the type of database to obtain? After searching on the Internet for a long time, I finally got something. As follows:
If you use spring's jdbcTemplate, you can get it like this:
DatabaseMetaData md = this.jdbcTemplate.getDataSource().getConnection().getMetaData();
		System.out.println(md.getDatabaseProductName());
		System.out.println(md.getDatabaseProductVersion());


If it is a dataSource configured by yourself, you can directly get the Connection, and then get the DatabaseMetaData, such as:
try {
      String url = "jdbc:odbc:yourdatabasename";
      String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
      String user = "guest";
      String password = "guest";

      Class.forName(driver);
      Connection connection = DriverManager.getConnection(url, user, password);
      DatabaseMetaData meta = connection.getMetaData();

      System.out.println("We are using " + meta.getDatabaseProductName());
      System.out.println("Version is " + meta.getDatabaseProductVersion() );

      connection.close();
    } catch (Exception e) {
      System.err.println(e);
    }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327045071&siteId=291194637