工作中经常有告诉了一个数据库服务器JDBC连接信息,而不说数据库版本的,以致开发时不敢用该种数据库最新的特性。我写了一段小程序,用于探测远端数据库服务器类型:
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.SQLException; public class DBVersionDetector { public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { //Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance(); //Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:test", "oral", "oral"); Connection conn = DriverManager.getConnection("jdbc:db2://localhost:50000/sample", "db2admin", "db2admin"); DatabaseMetaData meta = conn.getMetaData(); System.out.println("URL:/t" + meta.getURL()); System.out.println("UserName:/t" + meta.getUserName()); System.out.println("DatabaseProductName:/t" + meta.getDatabaseProductName()); System.out.println("DatabaseMajorVersion:/t" + meta.getDatabaseMajorVersion()); System.out.println("DatabaseMinorVersion:/t" + meta.getDatabaseMinorVersion()); System.out.println("DatabaseProductVersion:/t" + meta.getDatabaseProductVersion()); System.out.println("DriverName:/t" + meta.getDriverName()); System.out.println("DriverMajorVersion:/t" + meta.getDriverMajorVersion()); System.out.println("DriverMinorVersion:/t" + meta.getDriverMinorVersion()); System.out.println("DriverVersion:/t" + meta.getDriverVersion()); System.out.println("JDBCMajorVersion:/t" + meta.getJDBCMajorVersion()); System.out.println("JDBCMinorVersion:/t" + meta.getJDBCMinorVersion()); conn.close(); } }
运行结果如下(示例):
URL: jdbc:db2://localhost:50000/sample UserName: db2admin DatabaseProductName: DB2/NT DatabaseMajorVersion: 9 DatabaseMinorVersion: 7 DatabaseProductVersion: SQL09070 DriverName: IBM DB2 JDBC Universal Driver Architecture DriverMajorVersion: 3 DriverMinorVersion: 57 DriverVersion: 3.57.82 JDBCMajorVersion: 3 JDBCMinorVersion: 0
从这里能看出这是一个DB2 v9.7 for Windows的服务器,支持JDBC3.0。