Java Code Examples for java.sql.Connection#isValid()
The following examples show how to use
java.sql.Connection#isValid() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DBHealthCheck.java From boost with Eclipse Public License 1.0 | 7 votes |
@Override public HealthCheckResponse call() { HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("membership"); try { Connection connection = datasource.getConnection(); boolean isValid = connection.isValid(5); DatabaseMetaData metaData = connection.getMetaData(); responseBuilder = responseBuilder .withData("databaseProductName", metaData.getDatabaseProductName()) .withData("databaseProductVersion", metaData.getDatabaseProductVersion()) .withData("driverName", metaData.getDriverName()) .withData("driverVersion", metaData.getDriverVersion()) .withData("isValid", isValid); return responseBuilder.state(isValid).build(); } catch(SQLException e) { responseBuilder = responseBuilder .withData("exceptionMessage", e.getMessage()); return responseBuilder.down().build(); } }
Example 2
Source File: BasicConnectionPool.java From tutorials with MIT License | 6 votes |
@Override public Connection getConnection() throws SQLException { if (connectionPool.isEmpty()) { if (usedConnections.size() < MAX_POOL_SIZE) { connectionPool.add(createConnection(url, user, password)); } else { throw new RuntimeException("Maximum pool size reached, no available connections!"); } } Connection connection = connectionPool.remove(connectionPool.size() - 1); if(!connection.isValid(MAX_TIMEOUT)){ connection = createConnection(url, user, password); } usedConnections.add(connection); return connection; }
Example 3
Source File: MySQLCore.java From QuickShop-Reremake with GNU General Public License v3.0 | 6 votes |
/** * Gets the database connection for executing queries on. * * @return The database connection */ @Nullable @Override public Connection getConnection() { for (int i = 0; i < MAX_CONNECTIONS; i++) { Connection connection = POOL.get(i); try { // If we have a current connection, fetch it if (connection != null && !connection.isClosed()) { if (connection.isValid(10)) { return connection; } // Else, it is invalid, so we return another connection. } connection = DriverManager.getConnection(this.url, info); POOL.set(i, connection); return connection; } catch (SQLException e) { e.printStackTrace(); } } return null; }
Example 4
Source File: ConnectionManager.java From es_data_export with Apache License 2.0 | 6 votes |
/** * 验证数据库连接是否有效 * @return * @throws SQLException */ public boolean isValid() throws SQLException{ Connection con = cpds.getConnection(); try { if(con!=null){ return con.isValid(10); } } catch (Exception e) { throw e; }finally { if(con!=null){ con.close(); } } return false; }
Example 5
Source File: MakeDefaultCatalogAction.java From netbeans with Apache License 2.0 | 6 votes |
/** * If DDL exception was caused by a closed connection, log info and display * a simple error dialog. Otherwise let users report the exception. */ private void handleDLLException(DatabaseConnection dbConn, DDLException e) throws SQLException, MissingResourceException { Connection conn = dbConn == null ? null : dbConn.getJDBCConnection(); if (conn != null && !conn.isValid(1000)) { LOGGER.log(Level.INFO, e.getMessage(), e); NotifyDescriptor nd = new NotifyDescriptor.Message( NbBundle.getMessage( MakeDefaultCatalogAction.class, "ERR_ConnectionToServerClosed"), //NOI18N NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notifyLater(nd); } else { Exceptions.printStackTrace(e); } }
Example 6
Source File: DBHealthCheck.java From microprofile-sandbox with Apache License 2.0 | 6 votes |
@Override public HealthCheckResponse call() { HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named("membership"); try { Connection connection = datasource.getConnection(); boolean isValid = connection.isValid(5); DatabaseMetaData metaData = connection.getMetaData(); responseBuilder = responseBuilder .withData("databaseProductName", metaData.getDatabaseProductName()) .withData("databaseProductVersion", metaData.getDatabaseProductVersion()) .withData("driverName", metaData.getDriverName()) .withData("driverVersion", metaData.getDriverVersion()) .withData("isValid", isValid); return responseBuilder.state(isValid).build(); } catch(SQLException e) { responseBuilder = responseBuilder .withData("exceptionMessage", e.getMessage()); return responseBuilder.down().build(); } }
Example 7
Source File: MysqlConnFactory.java From migration-tool with Apache License 2.0 | 6 votes |
@Override public boolean validateObject(PooledObject<Connection> p) { if(null == p) { return false; } Connection conn = p.getObject(); try { return conn.isValid(1); } catch (SQLException e) { log.error("连接不可用," + conn.toString()); if(null != conn) { try { conn.close(); } catch (SQLException e1) { log.error("连接关闭失败," + conn.toString(), e1); } } } return false; }
Example 8
Source File: MyDataSourceImpl.java From HotelSystem with Apache License 2.0 | 6 votes |
/** * 负责从数据库连接池中获取数据库连接 * * @return java.sql.Connection * @throws DaoException 如果数据库连接已经达到最大值时仍然调用此方法,则抛出此异常 * @name getConnection * @notice 数据库连接的数量受到配置文件中最大值的限制 * @author <a href="mailto:[email protected]">黄钰朝</a> * @date 2019/4/8 */ @Override public Connection getConnection() throws DaoException { if (connPool.size() > 0) { /** * 先检查连接是否可用,如果不可用,关闭该连接,返回一个新连接 */ Connection conn = connPool.removeLast(); try { if(conn.isValid(TIMEOUT)){ return conn; }else { destroyConnection(conn); return createConnection(); } } catch (SQLException e) { throw new DaoException("测试数据库连接产生异常",e); } } else if (currentCount < MAX_SIZE) { return createConnection(); } else { throw new DaoException("数据库连接数已达到最大值"); } }
Example 9
Source File: DatabaseUtils.java From StatsAgg with Apache License 2.0 | 6 votes |
public static boolean isConnectionValid(Connection connection, int timeoutInSeconds) { long startTime = System.currentTimeMillis(); try { if (connection == null) { return false; } else if (!connection.isValid(timeoutInSeconds)) { return false; } else { return true; } } catch (Exception e) { long timeElapsed = System.currentTimeMillis() - startTime; logger.error("Method=IsConnectionValid" + ", TimeElapsed=" + timeElapsed + ", Exception=" + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); return false; } }
Example 10
Source File: AbstractRevisionService.java From dkpro-jwpl with Apache License 2.0 | 6 votes |
/** * Helper method to obtain a connection via the given {@link RevisionAPIConfiguration} parameter. * @param config Must not be {@code null}. * @return A valid {@link Connection} to the database endpoint. * @throws WikiApiException Thrown if errors occurred while opening a connection. */ protected Connection getConnection(RevisionAPIConfiguration config) throws WikiApiException { Connection c; try { String driverDB = config.getDatabaseDriver(); Class.forName(driverDB); c = DriverManager.getConnection(config.getJdbcURL(), config.getUser(), config.getPassword()); if (!c.isValid(5)) { throw new WikiApiException("Connection could not be established."); } } catch (SQLException | ClassNotFoundException e) { throw new WikiApiException(e); } return c; }
Example 11
Source File: MySQLDB.java From Plan with GNU Lesser General Public License v3.0 | 6 votes |
@Override public synchronized Connection getConnection() throws SQLException { Connection connection = dataSource.getConnection(); if (!connection.isValid(5)) { connection.close(); if (dataSource instanceof HikariDataSource) { ((HikariDataSource) dataSource).close(); } try { setupDataSource(); // get new connection after restarting pool connection = dataSource.getConnection(); } catch (DBInitException e) { throw new DBOpException("Failed to restart DataSource after a connection was invalid: " + e.getMessage(), e); } } if (connection.getAutoCommit()) connection.setAutoCommit(false); return connection; }
Example 12
Source File: ConnectionRegressionTest.java From r-course with MIT License | 5 votes |
/** * Tests fix for Bug#56122 - JDBC4 functionality failure when using replication connections. */ public void testBug56122() throws Exception { for (final Connection testConn : new Connection[] { this.conn, getFailoverConnection(), getLoadBalancedConnection(), getMasterSlaveReplicationConnection() }) { testConn.createClob(); testConn.createBlob(); testConn.createNClob(); testConn.createSQLXML(); testConn.isValid(12345); testConn.setClientInfo(new Properties()); testConn.setClientInfo("NAME", "VALUE"); testConn.getClientInfo(); testConn.getClientInfo("CLIENT"); assertThrows(SQLFeatureNotSupportedException.class, new Callable<Void>() { public Void call() throws Exception { testConn.createArrayOf("A_TYPE", null); return null; } }); assertThrows(SQLFeatureNotSupportedException.class, new Callable<Void>() { public Void call() throws Exception { testConn.createStruct("A_TYPE", null); return null; } }); } }
Example 13
Source File: DefaultBackend.java From dbtransfer with GNU Lesser General Public License v2.1 | 5 votes |
@Override public boolean isValid(Connection con) throws SQLException { return con.isValid( CONNECTION_CHECK_TIMEOUT_MS ); }
Example 14
Source File: DataSourceValidator.java From dal with Apache License 2.0 | 5 votes |
private boolean connectionIsValid(Connection connection) throws SQLException { boolean isValid; if (connection instanceof MySQLConnection) { MySQLConnection mySqlConnection = (MySQLConnection) connection; isValid = MySqlConnectionHelper.isValid(mySqlConnection, DEFAULT_VALIDATE_TIMEOUT_IN_SECONDS); } else { isValid = connection.isValid(DEFAULT_VALIDATE_TIMEOUT_IN_SECONDS); } return isValid; }
Example 15
Source File: ConnectionRegressionTest.java From Komondor with GNU General Public License v3.0 | 5 votes |
/** * Tests fix for Bug#56122 - JDBC4 functionality failure when using replication connections. */ public void testBug56122() throws Exception { for (final Connection testConn : new Connection[] { this.conn, getFailoverConnection(), getLoadBalancedConnection(), getMasterSlaveReplicationConnection() }) { testConn.createClob(); testConn.createBlob(); testConn.createNClob(); testConn.createSQLXML(); testConn.isValid(12345); testConn.setClientInfo(new Properties()); testConn.setClientInfo("NAME", "VALUE"); testConn.getClientInfo(); testConn.getClientInfo("CLIENT"); assertThrows(SQLFeatureNotSupportedException.class, new Callable<Void>() { public Void call() throws Exception { testConn.createArrayOf("A_TYPE", null); return null; } }); assertThrows(SQLFeatureNotSupportedException.class, new Callable<Void>() { public Void call() throws Exception { testConn.createStruct("A_TYPE", null); return null; } }); } }
Example 16
Source File: RemoteDriverTest.java From calcite-avatica with Apache License 2.0 | 5 votes |
@Test public void testIsValid() throws Exception { ConnectionSpec.getDatabaseLock().lock(); try { final Connection connection = getLocalConnection(); try { connection.isValid(-1); fail("Connection isValid should throw SQLException on negative timeout"); } catch (SQLException expected) { assertEquals("timeout is less than 0", expected.getMessage()); } // Check that connection isValid before and during use assertThat(connection.isValid(1), is(true)); Statement statement = connection.createStatement(); assertTrue(statement.execute("VALUES 1")); assertNotNull(statement.getResultSet()); assertThat(connection.isValid(1), is(true)); statement.close(); assertThat(connection.isValid(1), is(true)); // Connection should be invalid after being closed connection.close(); assertThat(connection.isValid(1), is(false)); } finally { ConnectionSpec.getDatabaseLock().unlock(); } }
Example 17
Source File: RDBConnectionPool.java From phoebus with Eclipse Public License 1.0 | 5 votes |
/** Get a connection * * <p>The connection should not be closed * but returned to the pool. * * @return {@link Connection} * @throws Exception on error * @see #releaseConnection(Connection) */ public Connection getConnection() throws Exception { if (closed) throw new Exception(this + " is closed"); Connection connection = pop(); while (connection != null) { // Is existing connection still good? if (connection.isValid(5)) { logger.log(Level.FINER, () -> "Reusing connection of " + this); if (total_connections != null) total_connections.put(connection, new Exception("Reuse connection " + this)); return connection; } // Close it close(connection); // Check next existing connection connection = pop(); } // No suitable existing connection, create new one connection = info.connect(); if (total_connections != null) { total_connections.put(connection, new Exception("Open connection " + this)); final int t = total_connections.size(); logger.log(Level.FINE, "New total connection count: " + t); } return connection; }
Example 18
Source File: BasicRetrySQLFailureHandler.java From aliyun-maxcompute-data-collectors with Apache License 2.0 | 4 votes |
/** * Verify the provided connection is valid. */ protected boolean validateConnection(Connection connection) throws SQLException { return connection != null && !connection.isClosed() && connection.isValid(DEFAULT_RETRY_WAIT_INTERVAL); }
Example 19
Source File: DataSourceValidator.java From das with Apache License 2.0 | 4 votes |
@Override public boolean validate(Connection connection, int validateAction) { boolean isValid = false; try { String query = null; int validationQueryTimeout = -1; if (validateAction == PooledConnection.VALIDATE_INIT) { PoolProperties poolProperties = getPoolProperties(connection); if (poolProperties != null) { query = poolProperties.getInitSQL(); validationQueryTimeout = poolProperties.getValidationQueryTimeout(); if (validationQueryTimeout <= 0) { validationQueryTimeout = DEFAULT_VALIDATE_TIMEOUT_IN_SECONDS; } } } if (query == null) { if (connection instanceof MySQLConnection) { MySQLConnection mySqlConnection = (MySQLConnection) connection; isValid = MySqlConnectionHelper.isValid(mySqlConnection, DEFAULT_VALIDATE_TIMEOUT_IN_SECONDS); } else { isValid = connection.isValid(DEFAULT_VALIDATE_TIMEOUT_IN_SECONDS); } if (!isValid) { LOGGER.warn("isValid() returned false."); } } else { Statement stmt = null; try { stmt = connection.createStatement(); stmt.setQueryTimeout(validationQueryTimeout); stmt.execute(query); isValid = true; } finally { if (stmt != null) { try { stmt.close(); } catch (Exception ignore2) { /* NOOP */} } } } } catch (Throwable ex) { LOGGER.warn("Datasource validation error", ex); } return isValid; }