java.sql.Connection#isValid ( )源码实例Demo

下面列出了java.sql.Connection#isValid ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: boost   文件: DBHealthCheck.java
@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();
    }
}
 
源代码2 项目: HotelSystem   文件: MyDataSourceImpl.java
/**
 * 负责从数据库连接池中获取数据库连接
 *
 * @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("数据库连接数已达到最大值");
    }
}
 
源代码3 项目: QuickShop-Reremake   文件: MySQLCore.java
/**
 * 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;
}
 
源代码4 项目: es_data_export   文件: ConnectionManager.java
/**
 * 验证数据库连接是否有效
 * @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;
}
 
源代码5 项目: netbeans   文件: MakeDefaultCatalogAction.java
/**
 * 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);
    }
}
 
源代码6 项目: microprofile-sandbox   文件: DBHealthCheck.java
@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();
    }
}
 
源代码7 项目: Plan   文件: MySQLDB.java
@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;
}
 
源代码8 项目: dkpro-jwpl   文件: AbstractRevisionService.java
/**
 * 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;
}
 
源代码9 项目: StatsAgg   文件: DatabaseUtils.java
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;
    } 
    
}
 
源代码10 项目: migration-tool   文件: MysqlConnFactory.java
@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;
}
 
源代码11 项目: tutorials   文件: BasicConnectionPool.java
@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;
}
 
源代码12 项目: phoebus   文件: RDBConnectionPool.java
/** 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;
}
 
源代码13 项目: r-course   文件: ConnectionRegressionTest.java
/**
 * 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;
            }
        });
    }
}
 
源代码14 项目: calcite-avatica   文件: RemoteDriverTest.java
@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();
  }
}
 
源代码15 项目: Komondor   文件: ConnectionRegressionTest.java
/**
 * 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;
            }
        });
    }
}
 
源代码16 项目: dal   文件: DataSourceValidator.java
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;
}
 
源代码17 项目: dbtransfer   文件: DefaultBackend.java
@Override
public boolean isValid(Connection con)
	throws SQLException

{
	return con.isValid( CONNECTION_CHECK_TIMEOUT_MS );
}
 
源代码18 项目: das   文件: DataSourceValidator.java
@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;
}
 
/**
 * Verify the provided connection is valid.
 */
protected boolean validateConnection(Connection connection)
    throws SQLException {
  return connection != null && !connection.isClosed()
    && connection.isValid(DEFAULT_RETRY_WAIT_INTERVAL);
}