📄 connectiontest.java
字号:
fail("Should have failed with an exception"); } catch (SQLException sqlEx) { // ignore for now } // // This feature caused BUG#8975, so check for that too! Properties props = new Properties(); props.setProperty("autoReconnect", "true"); getConnectionWithProps(props); } public void testSessionVariables() throws Exception { String getInitialMaxAllowedPacket = getMysqlVariable("max_allowed_packet"); int newMaxAllowedPacket = Integer.parseInt(getInitialMaxAllowedPacket) + 1024; Properties props = new Properties(); props.setProperty("sessionVariables", "max_allowed_packet=" + newMaxAllowedPacket); props.setProperty("profileSQL", "true"); Connection varConn = getConnectionWithProps(props); assertTrue(!getInitialMaxAllowedPacket.equals(getMysqlVariable(varConn, "max_allowed_packet"))); } /** * Tests setting profileSql on/off in the span of one connection. * * @throws Exception * if an error occurs. */ public void testSetProfileSql() throws Exception { ((com.mysql.jdbc.Connection) this.conn).setProfileSql(false); stmt.executeQuery("SELECT 1"); ((com.mysql.jdbc.Connection) this.conn).setProfileSql(true); stmt.executeQuery("SELECT 1"); } public void testCreateDatabaseIfNotExist() throws Exception { if (isAdminConnectionConfigured()) { Properties props = new Properties(); props.setProperty("createDatabaseIfNotExist", "true"); props.setProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY, "testcreatedatabaseifnotexists"); Connection newConn = getAdminConnectionWithProps(props); newConn.createStatement().executeUpdate( "DROP DATABASE testcreatedatabaseifnotexists"); } } /** * Tests if gatherPerfMetrics works. * * @throws Exception if the test fails */ public void testGatherPerfMetrics() throws Exception { if(versionMeetsMinimum(4, 1)) { try { Properties props = new Properties(); props.put("autoReconnect", "true"); props.put("relaxAutoCommit", "true"); props.put("logSlowQueries", "true"); props.put("slowQueryThresholdMillis", "2000"); // these properties were reported as the cause of NullPointerException props.put("gatherPerfMetrics", "true"); props.put("reportMetricsIntervalMillis", "3000"); Connection conn1 = getConnectionWithProps(props); Statement stmt1 = conn1.createStatement(); ResultSet rs1 = stmt1.executeQuery("SELECT 1"); rs1.next(); conn1.close(); } catch (NullPointerException e) { e.printStackTrace(); fail(); } } } /** * Tests if useCompress works. * * @throws Exception if the test fails */ public void testUseCompress() throws Exception { Properties props = new Properties(); props.put("useCompression", "true"); props.put("traceProtocol", "true"); Connection conn1 = getConnectionWithProps(props); Statement stmt1 = conn1.createStatement(); ResultSet rs1 = stmt1.executeQuery("SELECT VERSION()"); rs1.next(); rs1.getString(1); stmt1.close(); conn1.close(); } /** * Tests feature of "localSocketAddress", by enumerating local IF's and * trying each one in turn. This test might take a long time to run, since * we can't set timeouts if we're using localSocketAddress. We try and keep * the time down on the testcase by spawning the checking of each interface * off into separate threads. * * @throws Exception if the test can't use at least one of the local machine's * interfaces to make an outgoing connection to the server. */ public void testLocalSocketAddress() throws Exception { if (isRunningOnJdk131()) { return; } Enumeration allInterfaces = NetworkInterface.getNetworkInterfaces(); SpawnedWorkerCounter counter = new SpawnedWorkerCounter(); List allChecks = new ArrayList(); while (allInterfaces.hasMoreElements()) { NetworkInterface intf = (NetworkInterface)allInterfaces.nextElement(); Enumeration allAddresses = intf.getInetAddresses(); allChecks.add(new LocalSocketAddressCheckThread(allAddresses, counter)); } counter.setWorkerCount(allChecks.size()); for (Iterator it = allChecks.iterator(); it.hasNext();) { LocalSocketAddressCheckThread t = (LocalSocketAddressCheckThread)it.next(); t.start(); } // Wait for tests to complete.... synchronized (counter) { while (counter.workerCount > 0 /* safety valve */) { counter.wait(); if (counter.workerCount == 0) { System.out.println("Done!"); break; } } } boolean didOneWork = false; boolean didOneFail = false; for (Iterator it = allChecks.iterator(); it.hasNext();) { LocalSocketAddressCheckThread t = (LocalSocketAddressCheckThread)it.next(); if (t.atLeastOneWorked) { didOneWork = true; break; } else { if (!didOneFail) { didOneFail = true; } } } assertTrue("At least one connection was made with the localSocketAddress set", didOneWork); NonRegisteringDriver d = new NonRegisteringDriver(); String hostname = d.host(d.parseURL(dbUrl, null)); if (!hostname.startsWith(":") && !hostname.startsWith("localhost")) { int indexOfColon = hostname.indexOf(":"); if (indexOfColon != -1) { hostname = hostname.substring(0, indexOfColon); } boolean isLocalIf = false; isLocalIf = (null != NetworkInterface.getByName(hostname)); if (!isLocalIf) { try { isLocalIf = (null != NetworkInterface.getByInetAddress(InetAddress.getByName(hostname))); } catch (Throwable t) { isLocalIf = false; } } if (!isLocalIf) { assertTrue("At least one connection didn't fail with localSocketAddress set", didOneFail); } } } class SpawnedWorkerCounter { private int workerCount = 0; synchronized void setWorkerCount(int i) { workerCount = i; } synchronized void decrementWorkerCount() { workerCount--; notify(); } } class LocalSocketAddressCheckThread extends Thread { boolean atLeastOneWorked = false; Enumeration allAddresses = null; SpawnedWorkerCounter counter = null; LocalSocketAddressCheckThread(Enumeration e, SpawnedWorkerCounter c) { allAddresses = e; counter = c; } public void run() { while (allAddresses.hasMoreElements()) { InetAddress addr = (InetAddress)allAddresses.nextElement(); try { Properties props = new Properties(); props.setProperty("localSocketAddress", addr.getHostAddress()); props.setProperty("connectTimeout", "2000"); getConnectionWithProps(props).close(); atLeastOneWorked = true; break; } catch (SQLException sqlEx) { // ignore, we're only seeing if one of these tests succeeds } } counter.decrementWorkerCount(); } } public void testUsageAdvisorTooLargeResultSet() throws Exception { Connection uaConn = null; PrintStream stderr = System.err; StringBuffer logBuf = new StringBuffer(); StandardLogger.bufferedLog = logBuf; try { Properties props = new Properties(); props.setProperty("useUsageAdvisor", "true"); props.setProperty("resultSetSizeThreshold", "4"); props.setProperty("logger", "StandardLogger"); uaConn = getConnectionWithProps(props); assertTrue("Result set threshold message not present", logBuf.toString().indexOf("larger than \"resultSetSizeThreshold\" of 4 rows") != -1); } finally { System.setErr(stderr); closeMemberJDBCResources(); if (uaConn != null) { uaConn.close(); } } } public void testUseLocalSessionStateRollback() throws Exception { if (!versionMeetsMinimum(5, 0, 0)) { return; } Properties props = new Properties(); props.setProperty("useLocalSessionState", "true"); props.setProperty("profileSQL", "true"); StringBuffer buf = new StringBuffer(); StandardLogger.bufferedLog = buf; createTable("testUseLocalSessionState", "(field1 varchar(32)) ENGINE=InnoDB"); Connection localStateConn = null; Statement localStateStmt = null; try { localStateConn = getConnectionWithProps(props); localStateStmt = localStateConn.createStatement(); localStateConn.setAutoCommit(false); localStateStmt.executeUpdate("INSERT INTO testUseLocalSessionState VALUES ('abc')"); localStateConn.rollback(); localStateConn.rollback(); localStateStmt.executeUpdate("INSERT INTO testUseLocalSessionState VALUES ('abc')"); localStateConn.commit(); localStateConn.commit(); localStateStmt.close(); } finally { StandardLogger.bufferedLog = null; if (localStateStmt != null) { localStateStmt.close(); } if (localStateConn != null) { localStateConn.close(); } } int rollbackCount = 0; int rollbackPos = 0; String searchIn = buf.toString(); while (rollbackPos != -1) { rollbackPos = searchIn.indexOf("rollback", rollbackPos); if (rollbackPos != -1) { rollbackPos += "rollback".length(); rollbackCount++; } } assertEquals(1, rollbackCount); int commitCount = 0; int commitPos = 0; // space is important here, we don't want to count "autocommit" while (commitPos != -1) { commitPos = searchIn.indexOf(" commit", commitPos); if (commitPos != -1) { commitPos += " commit".length(); commitCount++; } } assertEquals(1, commitCount); } /** * Checks if setting useCursorFetch to "true" automatically * enables server-side prepared statements. */ public void testCouplingOfCursorFetch() throws Exception { if (!versionMeetsMinimum(5, 0)) { return; } Connection fetchConn = null; try { Properties props = new Properties(); props.setProperty("useServerPrepStmts", "false"); // force the issue props.setProperty("useCursorFetch", "true"); fetchConn = getConnectionWithProps(props); assertEquals("com.mysql.jdbc.ServerPreparedStatement", fetchConn.prepareStatement("SELECT 1").getClass().getName()); } finally { if (fetchConn != null) { fetchConn.close(); } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -