2015-12-12 88 views
2

我測試此代碼來獲得MySQL的版本:獲得MySQL版本與Java

public void testMySQLVersion() throws Exception 
    { 
     System.out.println("\nTesting SQL query for MySQL version\n"); 

     // Load the JDBC driver 
     DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); 

     // Connect to the database 
     Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@112.213.131.40:3306:webdb", "admin", "eHqtaXuc6h1w"); 

     PreparedStatement pstmt 
      = conn.prepareStatement("SHOW VARIABLES LIKE 'version'"); 

     ResultSet rset = pstmt.executeQuery(); 

     while (rset.next()) 
     { 
      System.out.println("MySQL version " + rset.getString("Value")); 
     } 

     pstmt.close(); 
     conn.close(); 
    } 

但是當我運行的代碼,我得到這樣的結果:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.634 sec <<< FAILURE! - in org.mysql.engine.osgi.impl.MySQLImplTest 
testMySQLVersion(org.mysql.engine.osgi.impl.MySQLImplTest) Time elapsed: 0.633 sec <<< ERROR! 
java.lang.StringIndexOutOfBoundsException: String index out of range: 12300 
    at java.lang.String.checkBounds(String.java:385) 
    at java.lang.String.<init>(String.java:324) 
    at oracle.net.ns.Packet.extractData(Packet.java:447) 
    at oracle.net.ns.RefusePacket.<init>(RefusePacket.java:70) 
    at oracle.net.ns.NSProtocolStream.negotiateConnection(NSProtocolStream.java:239) 
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:264) 
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452) 
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496) 
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:666) 
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32) 
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:566) 
    at java.sql.DriverManager.getConnection(DriverManager.java:664) 
    at java.sql.DriverManager.getConnection(DriverManager.java:247) 
    at org.mysql.engine.osgi.impl.MySQLImplTest.testMySQLVersion(MySQLImplTest.java:66) 

你能給我一些建議如何解決這個問題?

+6

您如何看待與Oracle相關的當前代碼可以與MySQL一起使用? – Reimeus

+0

@Reimeus好吧,因爲Oracle通過Sun收購MySQL,所以我猜Oracle#MySQL;) – Kayaman

+1

@Kayaman這是一個延伸,不確定在實踐中起作用:) – Reimeus

回答

6

要獲得數據庫版本,有一個更簡單的解決方案。一旦你有一個Connection到數據庫中,你可以得到它的元數據,並與getDatabaseProductVersion()從中提取的版本:

Connection con = ...; 
DatabaseMetaData meta = con.getMetaData(); 
System.out.println(meta.getDatabaseProductVersion()); 

這將爲MySQL或Oracle數據庫工作。

請注意,您當前的代碼很奇怪:您想獲取MySQL數據庫版本,但是您的SQL連接字符串與Oracle(jdbc:oracle:thin)有關。