Java Code Examples for com.alibaba.druid.util.JdbcUtils

The following examples show how to use com.alibaba.druid.util.JdbcUtils. These examples are extracted from open source projects. 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
private boolean computeTotalRecords() {
    Statement statement = null;
    ResultSet resultSet = null;
    Connection connection = null;
    try {
        connection = druidDataSource.getConnection();
        statement = connection.createStatement();
        resultSet = statement.executeQuery(String.format("select count(offset) as total from t_transaction_%d", tableSuffix));
        if (!resultSet.next()) {
            log.warn("computeTotalRecords ResultSet is empty");
            return false;
        }

        this.totalRecordsValue.set(resultSet.getLong(1));
    } catch (Exception e) {
        log.warn("computeTotalRecords Exception", e);
        return false;
    } finally {
        JdbcUtils.close(resultSet);
        JdbcUtils.close(statement);
        JdbcUtils.close(connection);
    }

    return true;
}
 
Example 2
private boolean createDB() {
    Statement statement = null;
    Connection connection = null;
    try {
        connection = druidDataSource.getConnection();
        connection.setAutoCommit(false);
        statement = connection.createStatement();
        String sql = this.createTableSql();
        log.info("createDB SQL:\n {}", sql);
        statement.execute(sql);
        connection.commit();
        return true;
    } catch (Exception e) {
        log.warn("createDB Exception", e);
        return false;
    } finally {
        JdbcUtils.close(statement);
        JdbcUtils.close(connection);
    }
}
 
Example 3
@Override
public long maxPK() {
    Connection connection = null;
    PreparedStatement ps = null;
    try {
        connection = druidDataSource.getConnection();
        ps = connection.prepareStatement(String.format("select max(offset) as maxOffset from t_transaction_%d", tableSuffix));
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            Long maxOffset = resultSet.getLong("maxOffset");
            return maxOffset != null ? maxOffset : -1L;
        }
    } catch (SQLException e) {
        log.warn("maxPK Exception", e);
    } finally {
        JdbcUtils.close(ps);
        JdbcUtils.close(connection);
    }
    return -1L;
}
 
Example 4
@Override
public long minPK() {
    Connection connection = null;
    PreparedStatement ps = null;
    try {
        connection = druidDataSource.getConnection();
        ps = connection.prepareStatement(String.format("select min(offset) as minOffset from t_transaction_%d", tableSuffix));
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            Long minOffset = resultSet.getLong("minOffset");
            return minOffset != null ? minOffset : -1L;
        }
    } catch (SQLException e) {
        log.warn("maxPK Exception", e);
    } finally {
        JdbcUtils.close(ps);
        JdbcUtils.close(connection);
    }
    return -1L;
}
 
Example 5
Source Project: spring-boot-starter-dao   Source File: DynamicDataSource.java    License: Apache License 2.0 6 votes vote down vote up
public DynamicDataSource(MybatisNodeProperties druidNode, DruidProperties defaultDruidProperties, String dataSourceName) throws SQLException {
	this.dataSourceName=dataSourceName;
	DruidProperties master = druidNode.getMaster();
	if (master == null)
		master = new DruidProperties();
	master.merge(defaultDruidProperties).defaultEmpty().setDefaultReadOnly(false);
	this.masterDataSource = master.createDataSource();
	this.masterDataSource.setName(dataSourceName + "-Master");
	List<DruidProperties> slaves = druidNode.getSlaves();
	if (slaves != null && !slaves.isEmpty()) {
		for (int i = 0; i < slaves.size(); i++) {
			DruidProperties slave = slaves.get(i);
			if (slave == null)
				continue;
			slave.merge(defaultDruidProperties).defaultEmpty().setDefaultReadOnly(true);
			String slaveDatasourceName = dataSourceName + "-Slave-" + i;
			this.slavesDataSourceNames.add(slaveDatasourceName);
			DruidDataSource datasourc = slave.createDataSource();
			datasourc.setName(slaveDatasourceName);
			this.slaveDataSources.put(slaveDatasourceName, datasourc);
		}
	}
	String rawUrl=master.getUrl();
	String dbType = JdbcUtils.getDbType(rawUrl,null);
	this.dialect=Dialect.valoueOfName(dbType);
}
 
Example 6
Source Project: Mycat2   Source File: TableMigrateInfo.java    License: GNU General Public License v3.0 6 votes vote down vote up
public  void setTableStructure() throws SQLException{
	DataNode dn = this.getOldDataNodes().get(0);
	Connection con = null;
	try {
		con = DataMigratorUtil.getMysqlConnection(dn);
		List<Map<String, Object>> list = DataMigratorUtil.executeQuery(con, "show create table "+tableName);
		Map<String, Object> m  = list.get(0);
		String str = m.get("Create Table").toString();
		str = str.replaceAll("CREATE TABLE", "Create Table if not exists");
		setTableStructure(str);
	} catch (SQLException e) {
		throw e;
	}finally {
		JdbcUtils.close(con);
	}
}
 
Example 7
Source Project: Mycat2   Source File: BinlogStream.java    License: GNU General Public License v3.0 6 votes vote down vote up
private Map<Integer, Map<String, Object>> loadColumn(String database, String table) {
    Map<Integer, Map<String, Object>> rtn = new HashMap<>();
    List<Map<String, Object>> list = null;
    Connection con = null;
    try {
        con = DriverManager.getConnection("jdbc:mysql://" + hostname + ":" + port, username, password);
        list = executeQuery(con, "select  COLUMN_NAME, ORDINAL_POSITION, DATA_TYPE, CHARACTER_SET_NAME from INFORMATION_SCHEMA.COLUMNS where table_name='" + table + "' and TABLE_SCHEMA='" + database + "'");

    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        JdbcUtils.close(con);
    }
    for (Map<String, Object> stringObjectMap : list) {
        BigInteger pos = (BigInteger) stringObjectMap.get("ORDINAL_POSITION");
        rtn.put(pos.intValue(), stringObjectMap);
    }
    return rtn;
}
 
Example 8
Source Project: Mycat2   Source File: MigrateUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void execulteSql(String sql, String toDn) throws SQLException, IOException {
    PhysicalDBNode dbNode = MycatServer.getInstance().getConfig().getDataNodes().get(toDn);
    PhysicalDBPool dbPool = dbNode.getDbPool();
    PhysicalDatasource datasource = dbPool.getSources()[dbPool.getActivedIndex()];
    DBHostConfig config = datasource.getConfig();
    Connection con = null;
    try {
        con = DriverManager
                .getConnection("jdbc:mysql://" + config.getUrl() + "/" + dbNode.getDatabase(), config.getUser(), config.getPassword());

        JdbcUtils.execute(con, sql, new ArrayList<>());

    } finally {
        JdbcUtils.close(con);
    }

}
 
Example 9
Source Project: Mycat2   Source File: MigrateUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static long execulteCount(String sql, String toDn) throws SQLException, IOException {
    PhysicalDBNode dbNode = MycatServer.getInstance().getConfig().getDataNodes().get(toDn);
    PhysicalDBPool dbPool = dbNode.getDbPool();
    PhysicalDatasource datasource = dbPool.getSources()[dbPool.getActivedIndex()];
    DBHostConfig config = datasource.getConfig();
    Connection con = null;
    try {
        con = DriverManager.getConnection("jdbc:mysql://" + config.getUrl() + "/" + dbNode.getDatabase(), config.getUser(), config.getPassword());

        List<Map<String, Object>> result = JdbcUtils.executeQuery(con, sql, new ArrayList<>());
        if (result.size() == 1) {
            return (long) result.get(0).get("count");
        }
    } finally {
        JdbcUtils.close(con);
    }
    return 0;
}
 
Example 10
Source Project: Mycat2   Source File: MigrateDumpRunner.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void loaddataToDn(File loaddataFile, String toDn, String table) throws SQLException, IOException {
    PhysicalDBNode dbNode = MycatServer.getInstance().getConfig().getDataNodes().get(toDn);
    PhysicalDBPool dbPool = dbNode.getDbPool();
    PhysicalDatasource datasource = dbPool.getSources()[dbPool.getActivedIndex()];
    DBHostConfig config = datasource.getConfig();
    Connection con = null;
    try {
        con = DriverManager.getConnection("jdbc:mysql://" + config.getUrl() + "/" + dbNode.getDatabase(), config.getUser(), config.getPassword());
        String sql = "load data local infile '" + loaddataFile.getPath().replace("\\", "//") + "' replace into table " + table + " character set 'utf8mb4'  fields terminated by ','  enclosed by '\"'  ESCAPED BY '\\\\'  lines terminated by '\\n'";
        JdbcUtils.execute(con, sql, new ArrayList<>());
    }
    catch (Exception e){
        try {
            pushMsgToZK(task.getZkpath(), task.getFrom() + "-" + task.getTo(), 0, e.getLocalizedMessage(), "", "");
        } catch (Exception e1) {
        }
    }
    finally {
        JdbcUtils.close(con);
    }
}
 
Example 11
Source Project: Mycat2   Source File: MigrateDumpRunner.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static String querySecurePath(DBHostConfig config) {
    List<Map<String, Object>> list = null;
    String path = null;
    Connection con = null;
    try {
        con = DriverManager.getConnection("jdbc:mysql://" + config.getUrl(), config.getUser(), config.getPassword());
        list = executeQuery(con, "show variables like 'secure_file_priv'");
        if (list != null && list.size() == 1)
            path = (String) list.get(0).get("Value");
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        JdbcUtils.close(con);
    }
    return path;
}
 
Example 12
protected void initCheck() throws SQLException {
    if (JdbcUtils.ORACLE.equals(this.dbType)) {
        isOracle = true;

        if (driver.getMajorVersion() < 10) {
            throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "."
                    + driver.getMinorVersion());
        }

        if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) {
            this.getConnectProperties().setProperty("oracle.jdbc.FreeMemoryOnEnterImplicitCache", "true");
        }

        oracleValidationQueryCheck();
    } else if (JdbcUtils.DB2.equals(dbType)) {
        db2ValidationQueryCheck();
    } else if (JdbcUtils.MYSQL.equals(this.dbType)
            || JdbcUtils.MYSQL_DRIVER_6.equals(this.dbType)) {
        isMySql = true;
    }

    if (removeAbandoned) {
        LOG.warn("removeAbandoned is true, not use in productiion.");
    }
}
 
Example 13
/**
 * 抛弃连接,不进行回收,而是抛弃
 *
 * @param realConnection
 */
public void discardConnection(Connection realConnection) {
    JdbcUtils.close(realConnection);

    lock.lock();
    try {
        activeCount--;
        discardCount++;

        if (activeCount <= minIdle) {
            emptySignal();
        }
    } finally {
        lock.unlock();
    }
}
 
Example 14
@Override
public boolean parpare(List<TransactionRecord> trs) {
    if (trs == null || trs.size() == 0) {
        return true;
    }
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = druidDataSource.getConnection();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(String.format("insert into t_transaction_%d (offset,producerGroup,timestamp,size) values (?, ?, ?, ?)", tableSuffix));
        for (TransactionRecord tr : trs) {
            statement.setLong(1, tr.getOffset());
            statement.setString(2, tr.getProducerGroup());
            statement.setLong(3, tr.getTimestamp());
            statement.setInt(4, tr.getSize());
            statement.addBatch();
        }
        int[] executeBatch = statement.executeBatch();
        connection.commit();
        this.totalRecordsValue.addAndGet(updatedRows(executeBatch));
        return true;
    } catch (Exception e) {
        log.warn("createDB Exception", e);
        return false;
    } finally {
        JdbcUtils.close(statement);
        JdbcUtils.close(connection);
    }
}
 
Example 15
@Override
public boolean confirm(List<Long> pks) {
    if (pks == null || pks.size() == 0) {
        return true;
    }
    PreparedStatement statement = null;
    Connection connection = null;
    try {
        connection = druidDataSource.getConnection();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(String.format("DELETE FROM t_transaction_%d WHERE offset = ?", tableSuffix));
        for (long pk : pks) {
            statement.setLong(1, pk);
            statement.addBatch();
        }
        int[] executeBatch = statement.executeBatch();
        connection.commit();
        this.totalRecordsValue.addAndGet(-updatedRows(executeBatch));
        return true;
    } catch (Exception e) {
        log.warn("createDB Exception", e);
    } finally {
        JdbcUtils.close(statement);
        JdbcUtils.close(connection);
    }
    return false;
}
 
Example 16
@Override
public List<TransactionRecord> traverse(long pk, int nums) {
    List<TransactionRecord> list = new ArrayList<TransactionRecord>(nums);
    Connection connection = null;
    PreparedStatement ps = null;
    try {
        connection = druidDataSource.getConnection();
        ps = connection.prepareStatement(String.format("select offset,producerGroup,timestamp,size from t_transaction_%d where offset>? order by offset limit ?", tableSuffix));
        ps.setLong(1, pk);
        ps.setInt(2, nums);
        ResultSet resultSet = ps.executeQuery();
        while (resultSet.next()) {
            TransactionRecord tr = new TransactionRecord(
                    resultSet.getLong("offset"),
                    resultSet.getLong("timestamp"),
                    resultSet.getInt("size"),
                    resultSet.getString("producerGroup")
            );
            list.add(tr);
        }
        return list;
    } catch (SQLException e) {
        log.warn("traverse Exception", e);
    } finally {
        JdbcUtils.close(ps);
        JdbcUtils.close(connection);
    }
    return list;
}
 
Example 17
protected String getDbType(DruidProperties nodeProperties, DruidProperties defaultProperties) {
	String rawUrl = nodeProperties.getUrl();
	if (StringUtils.isEmpty(nodeProperties.getUrl())) {
		rawUrl = defaultProperties.getUrl();
	}
	return JdbcUtils.getDbType(rawUrl, null);
}
 
Example 18
Source Project: Mycat2   Source File: EcachesxmlTozkLoader.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 读取 mapFile文件的信息
* 方法描述
* @param name 名称信息
* @return
* @创建日期 2016年9月18日
*/
private String readSeqFile(String name) {

    StringBuilder mapFileStr = new StringBuilder();

    String path = ZookeeperPath.ZK_LOCAL_CFG_PATH.getKey() + name;
    // 加载数据
    InputStream input = EcachesxmlTozkLoader.class.getResourceAsStream(path);

    checkNotNull(input, "read SeqFile file curr Path :" + path + " is null! must is not null");

    byte[] buffers = new byte[256];

    try {
        int readIndex = -1;

        while ((readIndex = input.read(buffers)) != -1) {
            mapFileStr.append(new String(buffers, 0, readIndex));
        }
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("EhcachexmlTozkLoader readMapFile IOException", e);
    } finally {
        JdbcUtils.close(input);
    }

    return mapFileStr.toString();
}
 
Example 19
Source Project: Mycat2   Source File: ServerxmlTozkLoader.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 读取 properties配制文件的信息
* 方法描述
* @param name 名称信息
* @return
* @创建日期 2016年9月18日
*/
private String readProperties(String name) {

    String path = ZookeeperPath.ZK_LOCAL_CFG_PATH.getKey() + name;
    // 加载数据
    InputStream input = SequenceTozkLoader.class.getResourceAsStream(path);

    if (null != input) {

        StringBuilder mapFileStr = new StringBuilder();

        byte[] buffers = new byte[256];

        try {
            int readIndex = -1;

            while ((readIndex = input.read(buffers)) != -1) {
                mapFileStr.append(new String(buffers, 0, readIndex));
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("SequenceTozkLoader readMapFile IOException", e);

        } finally {
            JdbcUtils.close(input);
        }

        return mapFileStr.toString();
    }
    return null;
}
 
Example 20
Source Project: Mycat2   Source File: SequenceTozkLoader.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 读取 sequence配制文件的信息
* 方法描述
* @param name 名称信息
* @return
* @创建日期 2016年9月18日
*/
private String readSequenceCfg(String name) {

    String path = ZookeeperPath.ZK_LOCAL_CFG_PATH.getKey() + name;
    // 加载数据
    InputStream input = SequenceTozkLoader.class.getResourceAsStream(path);

    if (null != input) {

        StringBuilder mapFileStr = new StringBuilder();

        byte[] buffers = new byte[256];

        try {
            int readIndex = -1;

            while ((readIndex = input.read(buffers)) != -1) {
                mapFileStr.append(new String(buffers, 0, readIndex));
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("SequenceTozkLoader readMapFile IOException", e);

        } finally {
            JdbcUtils.close(input);
        }

        return mapFileStr.toString();
    }
    return null;
}
 
Example 21
Source Project: Mycat2   Source File: RulesxmlTozkLoader.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 读取 mapFile文件的信息
* 方法描述
* @param name 名称信息
* @return
* @创建日期 2016年9月18日
*/
private String readMapFile(String name) {

    StringBuilder mapFileStr = new StringBuilder();

    String path = ZookeeperPath.ZK_LOCAL_CFG_PATH.getKey() + name;
    // 加载数据
    InputStream input = RulesxmlTozkLoader.class.getResourceAsStream(path);

    checkNotNull(input, "read Map file curr Path :" + path + " is null! must is not null");

    byte[] buffers = new byte[256];

    try {
        int readIndex = -1;

        while ((readIndex = input.read(buffers)) != -1) {
            mapFileStr.append(new String(buffers, 0, readIndex));
        }
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("RulesxmlTozkLoader readMapFile IOException", e);

    } finally {
        JdbcUtils.close(input);
    }

    return mapFileStr.toString();
}
 
Example 22
Source Project: Mycat2   Source File: DataClearRunner.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
	String data = "";
	long offset = 0;
	Connection con = null;
	try {
		long start = System.currentTimeMillis();
		con = DataMigratorUtil.getMysqlConnection(srcDn);
		if(tableInfo.isExpantion()){
			deleteDataDependFile(data, offset, con);
		}else{
			//缩容,移除的节点直接truncate删除数据,非移除的节点按照临时文件的中值进行删除操作
			List<DataNode> list = tableInfo.getRemovedDataNodes();
			boolean isRemovedDn = false;
			for(DataNode dn:list){
				if(srcDn.equals(dn)){
					isRemovedDn = true;
				}
			}
			if(isRemovedDn){
				String sql = "truncate "+tableInfo.getTableName();
				JdbcUtils.execute(con, sql, new ArrayList<>());
			}else{
				deleteDataDependFile(data, offset, con);
			}
		}
		long end = System.currentTimeMillis();
		System.out.println(tableInfo.getSchemaAndTableName()+" clean dataNode "+srcDn.getName()+" completed in "+(end-start)+"ms");
		
	} catch (Exception e) {
		String errMessage = srcDn.toString()+":"+"clean data error!";
		LOGGER.error(errMessage, e);
		tableInfo.setError(true);
		tableInfo.getErrMessage().append(errMessage+"\n");
	} finally{
		JdbcUtils.close(con);
	}
}
 
Example 23
Source Project: Mycat2   Source File: DataClearRunner.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void deleteDataDependFile(String data,long offset,Connection con) throws IOException, SQLException{
	while((data=DataMigratorUtil.readData(tempFile,offset,DataMigrator.margs.getQueryPageSize())).length()>0){
		offset += data.getBytes().length;
		if(data.startsWith(",")){
			data = data.substring(1, data.length());
		}
		if(data.endsWith(",")){
			data = data.substring(0,data.length()-1);
		}
		String sql = "delete from "+tableInfo.getTableName()+" where "+tableInfo.getColumn()+" in ("+data+")";
		JdbcUtils.execute(con, sql, new ArrayList<>());
	}
}
 
Example 24
Source Project: Mycat2   Source File: DataMigratorUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static long querySize(DataNode dn,String tableName) throws SQLException{
	List<Map<String, Object>> list=null;
	long size = 0L;
	Connection con = null;
	try {
		con =  getMysqlConnection(dn);
		list = executeQuery(con, "select count(1) size from "+tableName);
		size = (long) list.get(0).get("size");
	} catch (SQLException e) {
		throw e;
	}finally{
		JdbcUtils.close(con);
	}
	return size;
}
 
Example 25
Source Project: Mycat2   Source File: DataMigratorUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void createTable(DataNode dn,String table) throws SQLException{
	Connection con = null;
	try {
		con =  getMysqlConnection(dn);
		JdbcUtils.execute(con, table, new ArrayList<>());
	} catch (SQLException e) {
		throw e;
	}finally{
		JdbcUtils.close(con);
	}
}
 
Example 26
Source Project: Mycat2   Source File: MigrateDumpRunner.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void exeCreateTableToDn(String sql, String toDn, String table) throws SQLException {
    PhysicalDBNode dbNode = MycatServer.getInstance().getConfig().getDataNodes().get(toDn);
    PhysicalDBPool dbPool = dbNode.getDbPool();
    PhysicalDatasource datasource = dbPool.getSources()[dbPool.getActivedIndex()];
    DBHostConfig config = datasource.getConfig();
    Connection con = null;
    try {
        con = DriverManager.getConnection("jdbc:mysql://" + config.getUrl() + "/" + dbNode.getDatabase(), config.getUser(), config.getPassword());
        JdbcUtils.execute(con, sql, new ArrayList<>());
    } finally {
        JdbcUtils.close(con);
    }
}
 
Example 27
Source Project: Mycat2   Source File: PreparedStatement.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static String[] getColumns(String sql) {
    String[] columnNames;
    try {
        SQLStatementParser sqlStatementParser = SQLParserUtils.createSQLStatementParser(sql, JdbcUtils.MYSQL);
        SQLStatement statement = sqlStatementParser.parseStatement();
        if (statement instanceof SQLSelectStatement) {
            SQLSelect select = ((SQLSelectStatement) statement).getSelect();
            com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock query = (com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock) select.getQuery();
            int size = query.getSelectList().size();
            if (size == 1){
                if("*".equalsIgnoreCase(   query.getSelectList().get(0).toString())){
                    throw new Exception("unsupport * in select items:"+sql);
                }
            } {
                columnNames = new String[size];
                for (int i = 0; i < size; i++) {
                    columnNames[i] = query.getSelectList().get(i).toString();
                }
                return columnNames;
            }

        }
    }catch (Exception e){
        LOGGER.error("can not get column count",e);
    }
    return new String[]{};
}
 
Example 28
Source Project: coming   Source File: PGValidConnectionChecker_s.java    License: MIT License 5 votes vote down vote up
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
    if (validateQuery == null || validateQuery.isEmpty()) {
        validateQuery = this.defaultValidateQuery;
    }

    if (conn.isClosed()) {
        return false;
    }

    if (conn instanceof DruidPooledConnection) {
        conn = ((DruidPooledConnection) conn).getConnection();
    }

    if (conn instanceof ConnectionProxy) {
        conn = ((ConnectionProxy) conn).getRawObject();
    }

    int queryTimeout = validationQueryTimeout <= 0 ? defaultQueryTimeout : validationQueryTimeout;

    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = conn.createStatement();
        stmt.setQueryTimeout(queryTimeout);
        rs = stmt.executeQuery(validateQuery);
        return true;
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(stmt);
    }
}
 
Example 29
Source Project: coming   Source File: PGValidConnectionChecker_t.java    License: MIT License 5 votes vote down vote up
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
    if (validateQuery == null || validateQuery.isEmpty()) {
        validateQuery = this.defaultValidateQuery;
    }

    if (conn.isClosed()) {
        return false;
    }

    if (conn instanceof DruidPooledConnection) {
        conn = ((DruidPooledConnection) conn).getConnection();
    }

    if (conn instanceof ConnectionProxy) {
        conn = ((ConnectionProxy) conn).getRawObject();
    }

    int queryTimeout = validationQueryTimeout <= 0 ? defaultQueryTimeout : validationQueryTimeout;

    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = conn.createStatement();
        if(queryTimeout>=0){
            //pgsql Driver 9.0以及以下版本不支持setQueryTimeout,可通过设置queryTimeout<0兼容低版本
            stmt.setQueryTimeout(queryTimeout);
        }
        rs = stmt.executeQuery(validateQuery);
        return true;
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(stmt);
    }
}
 
Example 30
Source Project: metrics   Source File: DruidStatTest.java    License: Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() throws Exception {
    JdbcUtils.close(dataSource);
}