我测试了这段代码以获得MySQL版本:
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)
你能给我一些如何解决这个问题的建议吗?
答案 0 :(得分:7)
要获得数据库版本,有一个更简单的解决方案。获得Connection
数据库后,您可以使用getDatabaseProductVersion()
获取其元数据并从中提取其版本:
Connection con = ...;
DatabaseMetaData meta = con.getMetaData();
System.out.println(meta.getDatabaseProductVersion());
这适用于MySQL或Oracle数据库。
请注意,您当前的代码很奇怪:您希望获取MySQL数据库版本,但您的SQL连接字符串处理Oracle(jdbc:oracle:thin
)。