Example usage for java.sql Connection toString

List of usage examples for java.sql Connection toString

Introduction

In this page you can find the example usage for java.sql Connection toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler.java

public SampleResult sample(Entry e) {
    log.debug("sampling jdbc");

    SampleResult res = new SampleResult();
    res.setSampleLabel(getName());/*from   w w  w. jav  a2 s  .c om*/
    res.setSamplerData(toString());
    res.setDataType(SampleResult.TEXT);
    res.setContentType("text/plain"); // $NON-NLS-1$
    res.setDataEncoding(ENCODING);

    // Assume we will be successful
    res.setSuccessful(true);
    res.setResponseMessageOK();
    res.setResponseCodeOK();

    res.sampleStart();
    Connection conn = null;
    Statement stmt = null;

    try {

        try {
            conn = DataSourceElement.getConnection(getDataSource());
        } finally {
            res.latencyEnd(); // use latency to measure connection time
        }
        res.setResponseHeaders(conn.toString());

        // Based on query return value, get results
        String _queryType = getQueryType();
        if (SELECT.equals(_queryType)) {
            stmt = conn.createStatement();
            ResultSet rs = null;
            try {
                rs = stmt.executeQuery(getQuery());
                res.setResponseData(getStringFromResultSet(rs).getBytes(ENCODING));
            } finally {
                close(rs);
            }
        } else if (CALLABLE.equals(_queryType)) {
            CallableStatement cstmt = getCallableStatement(conn);
            int out[] = setArguments(cstmt);
            // A CallableStatement can return more than 1 ResultSets
            // plus a number of update counts.
            boolean hasResultSet = cstmt.execute();
            String sb = resultSetsToString(cstmt, hasResultSet, out);
            res.setResponseData(sb.getBytes(ENCODING));
        } else if (UPDATE.equals(_queryType)) {
            stmt = conn.createStatement();
            stmt.executeUpdate(getQuery());
            int updateCount = stmt.getUpdateCount();
            String results = updateCount + " updates";
            res.setResponseData(results.getBytes(ENCODING));
        } else if (PREPARED_SELECT.equals(_queryType)) {
            PreparedStatement pstmt = getPreparedStatement(conn);
            setArguments(pstmt);
            pstmt.executeQuery();
            String sb = resultSetsToString(pstmt, true, null);
            res.setResponseData(sb.getBytes(ENCODING));
        } else if (PREPARED_UPDATE.equals(_queryType)) {
            PreparedStatement pstmt = getPreparedStatement(conn);
            setArguments(pstmt);
            pstmt.executeUpdate();
            String sb = resultSetsToString(pstmt, false, null);
            res.setResponseData(sb.getBytes(ENCODING));
        } else if (ROLLBACK.equals(_queryType)) {
            conn.rollback();
            res.setResponseData(ROLLBACK.getBytes(ENCODING));
        } else if (COMMIT.equals(_queryType)) {
            conn.commit();
            res.setResponseData(COMMIT.getBytes(ENCODING));
        } else if (AUTOCOMMIT_FALSE.equals(_queryType)) {
            conn.setAutoCommit(false);
            res.setResponseData(AUTOCOMMIT_FALSE.getBytes(ENCODING));
        } else if (AUTOCOMMIT_TRUE.equals(_queryType)) {
            conn.setAutoCommit(true);
            res.setResponseData(AUTOCOMMIT_TRUE.getBytes(ENCODING));
        } else { // User provided incorrect query type
            String results = "Unexpected query type: " + _queryType;
            res.setResponseMessage(results);
            res.setSuccessful(false);
        }

    } catch (SQLException ex) {
        final String errCode = Integer.toString(ex.getErrorCode());
        res.setResponseMessage(ex.toString());
        res.setResponseCode(ex.getSQLState() + " " + errCode);
        res.setSuccessful(false);
    } catch (UnsupportedEncodingException ex) {
        res.setResponseMessage(ex.toString());
        res.setResponseCode("000"); // TODO - is this correct?
        res.setSuccessful(false);
    } catch (IOException ex) {
        res.setResponseMessage(ex.toString());
        res.setResponseCode("000"); // TODO - is this correct?
        res.setSuccessful(false);
    } finally {
        close(stmt);
        close(conn);
    }

    // TODO: process warnings? Set Code and Message to success?
    res.sampleEnd();
    return res;
}

From source file:org.apache.openejb.resource.jdbc.XAPoolTest.java

@Test
public void check() throws SQLException {
    assertNotNull(ds);/*  w  w w . ja  v a  2s.co  m*/
    final BasicDataSource tds = ManagedDataSourceWithRecovery.class.cast(ds);

    assertEquals(0, tds.getNumIdle()); // db not yet used so no connection at all (dbcp behavior)

    try (final Connection c = ds.getConnection()) {
        assertNotNull(c);

        final Connection connection = c.getMetaData().getConnection(); // just to do something and force the connection init
        assertThat(connection, instanceOf(ManagedConnection.class));
        assertTrue(connection.toString()
                .contains("URL=jdbc:hsqldb:mem:dbcpxa, UserName=SA, HSQL Database Engine Driver"));
    } // here we close the connection so we are back in the initial state

    assertEquals(0, tds.getNumActive());
    assertEquals(3, tds.getNumIdle());

    for (int it = 0; it < 5; it++) { // ensures it always works and not only the first time
        final Collection<Connection> connections = new ArrayList<>(25);
        for (int i = 0; i < 25; i++) {
            final Connection connection = ds.getConnection();
            connections.add(connection);
            connection.getMetaData(); // trigger connection retrieving otherwise nothing is done (pool is not used)
        }
        assertEquals(25, tds.getNumActive());
        assertEquals(0, tds.getNumIdle());
        for (final Connection toClose : connections) {
            toClose.close();
        }
        assertEquals(0, tds.getNumActive());
        assertEquals(25, tds.getNumIdle());
    }
}

From source file:org.apache.phoenix.trace.TraceWriter.java

protected Connection getConnection(String tableName) {

    try {//from   w  ww  .  j av a 2 s .  c  om
        // create the phoenix connection
        Properties props = new Properties();
        props.setProperty(QueryServices.TRACING_FREQ_ATTRIB, Tracing.Frequency.NEVER.getKey());
        Configuration conf = HBaseConfiguration.create();
        Connection conn = QueryUtil.getConnectionOnServer(props, conf);

        if (!traceTableExists(conn, tableName)) {
            createTable(conn, tableName);
        }

        LOG.info("Created new connection for tracing " + conn.toString() + " Table: " + tableName);
        return conn;
    } catch (Exception e) {
        LOG.error("Tracing will NOT be pursued. New connection failed for tracing Table: " + tableName, e);
        LOG.error("Restart Phoenix to retry.");
        return null;
    }
}

From source file:org.apache.phoenix.trace.TraceWriter.java

protected void commitBatch(Connection conn) {
    try {//from   w  w w  .j  ava 2  s. co  m
        conn.commit();
    } catch (SQLException e) {
        LOG.error("Unable to commit traces on conn: " + conn.toString() + " to table: " + tableName, e);
    }
}

From source file:org.apache.synapse.commons.transaction.TranscationManger.java

public static boolean checkConnectionAlreadyUse(Connection conn) throws SQLException {
    boolean isUsed = false;
    if (connections.containsValue(new ConnectionMapper(conn))) {
        isUsed = true;//www. j  a v a 2  s .com
        log.debug(" Connection toString : " + conn.toString());
    }

    return isUsed;
}

From source file:org.jetbrains.webdemo.database.MySqlConnector.java

private MySqlConnector() {
    try {/*from   ww  w .j  av  a  2s  .c  om*/
        InitialContext initCtx = new InitialContext();
        NamingContext envCtx = (NamingContext) initCtx.lookup("java:comp/env");
        dataSource = (DataSource) envCtx.lookup("jdbc/kotlin");
        Connection connection = dataSource.getConnection();
        databaseUrl = connection.toString();
        log.info("Connected to database: " + connection.toString());
        ErrorWriter.getInfoForLog("CONNECT_TO_DATABASE", "-1", "Connected to database: " + databaseUrl);
    } catch (Throwable e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e,
                SessionInfo.TypeOfRequest.WORK_WITH_DATABASE.name(), "unknown", databaseUrl);
    }
}

From source file:org.kepler.objectmanager.library.LibIndex.java

/**
 * Initialize the instance.//from   w  w w. ja  v a  2s. co m
 * 
 * @param conn
 */
private void initialize(Connection conn) {
    if (isDebugging)
        log.debug("initialize(" + conn.toString() + ")");
    _conn = conn;

    _libraryManager = LibraryManager.getInstance();

    try {
        // By creating the statement and keeping it around
        // make sure to close your resultsets to save memory
        _stmt = _conn.createStatement();

        _updateOrderPrepStmt = _conn
                .prepareStatement("update " + LIBRARY_INDEX_TABLE_NAME + " SET LFT=?, RGT=? WHERE LIID=?");
        _updateLsidPrepStmt = _conn
                .prepareStatement("update " + LIBRARY_INDEX_TABLE_NAME + " SET LSID=? WHERE LIID=?");

        _getLIIDForKarPrepStmt = _conn.prepareStatement("SELECT LIID FROM " + LIBRARY_ATTRIBUTES_TABLE_NAME
                + " WHERE NAME = '" + ATT_KARFILE + "' AND VALUE = ?");

        _getLIIDForXMLPrepStmt = _conn.prepareStatement("SELECT LIID FROM " + LIBRARY_ATTRIBUTES_TABLE_NAME
                + " WHERE NAME = '" + ATT_XMLFILE + "' AND VALUE = ?");

        _getLIIDForFolderPrepStmt = _conn.prepareStatement("SELECT LIID FROM " + LIBRARY_ATTRIBUTES_TABLE_NAME
                + " WHERE NAME = '" + ATT_FOLDER + "' AND VALUE = ?");

        _getLIIDForKarEntryPrepStmt = _conn.prepareStatement("SELECT LIID FROM " + LIBRARY_ATTRIBUTES_TABLE_NAME
                + " WHERE NAME = '" + ATT_KARENTRYPATH + "' AND VALUE = ?");

        _getLIIDForKarErrorPrepStmt = _conn.prepareStatement("SELECT LIID FROM " + LIBRARY_ATTRIBUTES_TABLE_NAME
                + " WHERE NAME = '" + ATT_KARFILE + "' AND VALUE = ?");

        _getLIIDForRepositoryPrepStmt = _conn.prepareStatement("SELECT LIID FROM "
                + LIBRARY_ATTRIBUTES_TABLE_NAME + " WHERE NAME = '" + ATT_REPOPATH + "' AND VALUE = ?");

        _getLIIDForOntologyNamePrepStmt = _conn.prepareStatement(
                "SELECT LIID FROM " + LIBRARY_INDEX_TABLE_NAME + " WHERE NAME = ? AND LEVEL = 1");

        _getLIIDForOntologyClassPrepStmt = _conn
                .prepareStatement("SELECT LIID FROM " + LIBRARY_INDEX_TABLE_NAME + " WHERE LSID = ?");

        _getNumRowsInLibraryIndexPrepStmt = _conn
                .prepareStatement("SELECT count(LIID) from " + LIBRARY_INDEX_TABLE_NAME);

        _getLIIDOfParentsPrepStmt = _conn.prepareStatement("SELECT LIID from " + LIBRARY_INDEX_TABLE_NAME
                + " WHERE LFT < ? AND RGT > ? " + "ORDER BY LEVEL");

        _getLIIDForParentAndNamePrepStmt = _conn.prepareStatement(
                "select liid from " + LIBRARY_INDEX_TABLE_NAME + " where parent = ? and name = ?");

        _getLIIDForNullParentAndNamePrepStmt = _conn.prepareStatement(
                "select LIID from " + LIBRARY_INDEX_TABLE_NAME + " where PARENT IS NULL AND NAME = ?");

        _getRangeForLIIDPrepStmt = _conn
                .prepareStatement("SELECT LFT,RGT from " + LIBRARY_INDEX_TABLE_NAME + " WHERE LIID = ?");

        _getLIIDForParentPrepStmt = _conn.prepareStatement(
                "SELECT liid FROM " + LIBRARY_INDEX_TABLE_NAME + " WHERE parent = ? ORDER BY TYPE,NAME");

        _getLftRgtSumPrepStmt = _conn
                .prepareStatement("select (sum(LFT) + sum(RGT)) FROM " + LIBRARY_INDEX_TABLE_NAME);

        _getLIIDRootsPrepStmt = _conn.prepareStatement(
                "SELECT LIID FROM " + LIBRARY_INDEX_TABLE_NAME + " WHERE LEVEL = 1 ORDER BY TYPE,NAME");

        _deleteLIIDFromLibraryAttributesPrepStmt = _conn
                .prepareStatement("DELETE FROM " + LIBRARY_ATTRIBUTES_TABLE_NAME + " WHERE LIID = ?");

        _insertIntoLibraryAttributesPrepStmt = _conn.prepareStatement(
                "INSERT INTO " + LIBRARY_ATTRIBUTES_TABLE_NAME + " (LIID,NAME,VALUE) values (?, ?, ?)");

        _getNumLIIDForLIIDAndLSIDPrepStmt = _conn.prepareStatement(
                "SELECT count(LIID) FROM " + LIBRARY_LSIDS_TABLE_NAME + " WHERE LIID = ? AND LSID = ?");

        _insertIntoLibraryLSIDsPrepStmt = _conn
                .prepareStatement("insert into " + LIBRARY_LSIDS_TABLE_NAME + " (LIID,LSID) values (?,?)");

    } catch (SQLException e) {
        e.printStackTrace();
    }

    // Share the connection with the LibSearch
    _searcher = new LibSearch(_conn);
    initSearchMap();

    setOrderedInsert(true);
}

From source file:org.kepler.objectmanager.library.LibSearch.java

/**
 * Initialize the instance.//from   ww  w.  ja va2  s . co m
 * 
 * @param conn
 */
public void initialize(Connection conn) {
    if (isDebugging)
        log.debug("initialize(" + conn.toString() + ")");
    _conn = conn;

    try {
        // By creating the statement and keeping it around
        // make sure to close your resultsets to save memory
        _stmt = _conn.createStatement();
        _insertPrepStmt = _conn.prepareStatement("insert into " + LIB_SEARCH_TABLE_NAME
                + " (sid, type, liid, searchstring) values ( ?, ?, ?, ? )");
        _deletePrepStmt = _conn.prepareStatement("delete from " + LIB_SEARCH_TABLE_NAME + " where liid = ?");
        _deleteAllPrepStmt = _conn.prepareStatement("delete from " + LIB_SEARCH_TABLE_NAME);

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:org.nuclos.server.database.SpringDataBaseHelper.java

/**
 * @return a connection from the given datasource. Must be closed by the caller in a finally block.
 * @precondition datasource != null/*from   w  w  w  . ja v  a  2 s.co m*/
 */
public String getCurrentConnectionInfo() {
    if (dataSource == null) {
        throw new NullArgumentException("datasource");
    }
    Connection conn = null;
    try {
        conn = dataSource.getConnection();
        return conn.toString() + " @schema=" + getDbAccess().getSchemaName();
    } catch (SQLException ex) {
        throw new CommonFatalException("Connection to datasource could not be initialized.", ex);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }
}

From source file:org.openkoala.koala.monitor.support.JdbcPoolStatusCollector.java

/**
 * ?/*  ww w .ja  v  a  2 s .c o m*/
 * @param conn
 * @return
 */
private String getConnectionId(Connection conn) {
    if (conn.getClass().getName().contains("Proxool")) {
        return conn.toString().split("\\(")[1].replace(")", "");
    }
    return null;
}