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:de.sqlcoach.db.jdbc.DBConnection.java

/**
 * Gets the pool connection.//from  w w w.  j  a  va2 s  .com
 * 
 * @return the pool connection
 * 
 * @throws NamingException
 *           the naming exception
 * @throws SQLException
 *           the SQL exception
 */
protected static DBConnection getPoolConnection(String dataSourceName) throws NamingException, SQLException {
    final Context initCtx = new InitialContext();
    final Context envCtx = (Context) initCtx.lookup("java:comp/env");

    final String name = "jdbc/" + dataSourceName;

    DBConnection dbconn = null;

    Integer connectionCnt = DBConnection.connectionCounter.get(dataSourceName);
    if (connectionCnt == null)
        connectionCnt = 0;

    if (log.isInfoEnabled()) {
        log.info("getPoolConnection ENTER [dataSource=" + dataSourceName + " connectionCnt=" + connectionCnt
                + "]");
    }

    // final DataSource ds = (DataSource)envCtx.lookup(name);
    // if (ds == null) {
    // log.error ("getPoolConnection : No DataSource for "+ name+ " !");
    // return null;
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : DataSource: "+ds.toString());
    // }

    // final Connection cn = ds.getConnection();
    final Connection cn = getSimpleConnection(dataSourceName);
    if (cn == null) { // Failed !
        log.error("getPoolConnection : No Connection for " + name + " ! (connectionCnt:" + connectionCnt + ")");
        return null;
    } else { // Success
        DBConnection.connectionCounter.put(dataSourceName, connectionCnt++);
        dbconn = new DBConnection(cn, connectionCnt, dataSourceName);
        if (log.isDebugEnabled())
            log.debug("getPoolConnection : Connection: " + cn.toString());
    }

    cn.setAutoCommit(false);

    // Set Oracle date format to YYYY-MM-DD
    // final java.sql.DatabaseMetaData dm = cn.getMetaData();
    // final String prodname = dm.getDatabaseProductName();
    // if (prodname.equalsIgnoreCase("Oracle")) { // Only for Oracle !!
    // try (Statement s = cn.createStatement()) {
    // s.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : ProductName=" + prodname + "\nALTER
    // SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
    // } catch (SQLException e) {
    // log.warn("getPoolConnection : ProductName="+prodname+"\nALTER SESSION SET
    // NLS_DATE_FORMAT = 'YYYY-MM-DD': ", e);
    // }
    // } else {
    // if (log.isDebugEnabled())
    // log.debug("getPoolConnection : Kein Oracle cn= "+cn+ "
    // ProductName="+prodname);
    // }

    if (log.isInfoEnabled())
        log.info("getPoolConnection LEAVE dbconn=" + dbconn);

    return dbconn;
}

From source file:com.tacitknowledge.util.migration.jdbc.util.SqlUtil.java

/**
 * Ensures the given connection, statement, and result are properly closed.
 *
 * @param conn the connection to close; may be <code>null</code>
 * @param stmt the statement to close; may be <code>null</code>
 * @param rs   the result set to close; may be <code>null</code>
 *///  www .  j a v  a  2s .c  o m
public static void close(Connection conn, Statement stmt, ResultSet rs) {
    if (rs != null) {
        try {
            log.debug("Closing ResultSet: " + rs.toString());
            rs.close();
        } catch (SQLException e) {
            log.error("Error closing ResultSet", e);
        }
    }

    if (stmt != null) {
        try {
            log.debug("Closing Statement: " + stmt.toString());
            stmt.close();
        } catch (SQLException e) {
            log.error("Error closing Statement", e);
        }
    }

    if (conn != null) {
        try {
            if (!conn.isClosed()) {
                log.debug("Closing Connection " + conn.toString());
                conn.close();
            } else {
                log.debug("Connection (" + conn.toString() + ") already closed.");
            }
        } catch (SQLException e) {
            log.error("Error closing Connection", e);
        }
    }
}

From source file:com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBeanTest.java

@Test
public void shouldCreateCreateTransactionAwareConnection() throws Exception {
    DataSource dataSource = mock(DataSource.class);
    this.factoryBean.setDataSource(dataSource);
    DatabaseDataSourceConnection dataSourceConnection = this.factoryBean.getObject();
    Connection connection = dataSourceConnection.getConnection();
    assertTrue(connection.toString() + " is not transaction aware",
            connection.toString().startsWith("Transaction-aware proxy"));
}

From source file:com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBeanTest.java

@Test
public void shouldNotWrapCreateTransactionAwareConnection() throws Exception {
    DataSource dataSource = new TransactionAwareDataSourceProxy(mock(DataSource.class));
    this.factoryBean.setDataSource(dataSource);
    DatabaseDataSourceConnection dataSourceConnection = this.factoryBean.getObject();
    Connection connection = dataSourceConnection.getConnection();
    assertTrue(connection.toString() + " is not transaction aware", connection.toString()
            .startsWith("Transaction-aware proxy for target Connection  from DataSource [Mock for DataSource"));
}

From source file:com.gs.obevo.db.impl.core.jdbc.JdbcHelper.java

private String displayConnection(Connection connection) {
    return "Connection[" + System.identityHashCode(connection) + "]: " + connection.toString();
}

From source file:com.glaf.base.test.service.MxMixFeatureTestService.java

@Transactional
public void run() {
    log.debug("-------------------start run-------------------");
    for (int i = 0; i < 2; i++) {
        SysLog bean = new SysLog();
        bean.setAccount("test");
        bean.setIp("127.0.0.1");
        bean.setOperate("add");
        sysLogService.create(bean);//from www  .ja  v  a 2s.  co m
    }

    String sql = "insert into SYS_LOG(ID, ACCOUNT, IP, CREATETIME, MODULEID, OPERATE, FLAG, TIMEMS) values (?, ?, ?, ?, ?, ?, ?, ?) ";
    Connection connection = null;
    PreparedStatement psmt = null;
    try {
        connection = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
        System.out.println("connection:" + connection.toString());
        psmt = connection.prepareStatement(sql);
        for (int i = 0; i < 2; i++) {
            psmt.setLong(1, idGenerator.nextId());
            psmt.setString(2, "test2");
            psmt.setString(3, "192.168.0.100");
            psmt.setTimestamp(4, DateUtils.toTimestamp(new Date()));
            psmt.setString(5, "xx");
            psmt.setString(6, "Y");
            psmt.setInt(7, 1);
            psmt.setLong(8, i * i);
            psmt.addBatch();
        }
        psmt.executeBatch();
        psmt.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
    }
    log.debug("-------------------end run-------------------");
}

From source file:net.ageto.gyrex.persistence.jdbc.pool.internal.commands.ListPools.java

private void printPool(final PoolDefinition pool) throws BackingStoreException {
    printf("Pool %s", pool.getPoolId());
    printf(StringUtils.EMPTY);/* www .j  a va 2s  .  c  om*/

    final Properties driverProperties = pool.getDriverProperties();
    if (!driverProperties.isEmpty()) {
        printf("Driver Properties:");
        final SortedSet<String> names = new TreeSet<String>();
        final Enumeration<?> propertyNames = driverProperties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            names.add((String) propertyNames.nextElement());
        }
        for (final String key : names) {
            printf("  %35s: %s", key, StringUtils.trimToEmpty(driverProperties.getProperty(key)));
        }
        printf(StringUtils.EMPTY);
    }

    printf("Pool Statistics:");
    final BoneCPDataSource dataSource = (BoneCPDataSource) PoolActivator.getInstance().getRegistry()
            .getDataSource(pool.getPoolId());

    // test connectivity (this also works around a bug in BoneCP which would result in an NPE below)
    try {
        final Connection connection = dataSource.getConnection();
        if (connection instanceof ConnectionHandle) {
            printf("  %35s: %s", "connectionTest",
                    ((ConnectionHandle) connection).isValid(1000) ? "OK" : "NOT OK");
        } else {
            printf("  %35s: %s", "connectionSample", connection.toString());
        }
        connection.close();
    } catch (final SQLException e) {
        printf("  unable to connect to pool: %s", e.getMessage());
    }

    // total number of leased connections
    printf("  %35s: %d", "totalLeased", dataSource.getTotalLeased());
    printf(StringUtils.EMPTY);

    printf("Effective Pool Config:");
    final TreeMap<String, String> poolConfig = readPoolConfig(dataSource);
    for (final Entry<String, String> entry : poolConfig.entrySet()) {
        printf("  %35s: %s", entry.getKey(), entry.getValue());
    }
}

From source file:net.java.dev.simplepool.SimplePool.java

/**
 * Returns the local JDBC ID for a connection.
 *
 * @param conn The connection object./* ww w .  j a v a  2  s.c o  m*/
 *
 * @return The local JDBC ID for the connection.
 */
public int idOfConnection(Connection conn) {
    int match = -1;
    String tag;

    try {
        tag = conn.toString();
    } catch (NullPointerException e1) {
        tag = "none";
    }

    for (int i = 0; i < currConnections; i++) {
        if (connID[i].equals(tag)) {
            match = i;
            break;
        }
    }
    return match;
}

From source file:net.java.dev.simplepool.SimplePool.java

/**
 * Frees a connection. Replaces connection back into the main pool for reuse.
 *
 * @param conn The connection object./*  w  w  w  .  j  a  va2  s.c  o m*/
 *
 * @return  A status or empty string.
 */
public String freeConnection(Connection conn) {
    String res = "";

    int thisconn = idOfConnection(conn);
    if (thisconn >= 0) {
        connStatus[thisconn] = 0;
        res = "freed " + conn.toString();
        log.debug("Freed connection [" + String.valueOf(thisconn) + ']');
    } else {
        log.error("Could not free connection.");
    }

    return res;

}

From source file:com.glaf.core.jdbc.connection.DruidConnectionProvider.java

public Connection getConnection() throws SQLException {
    Connection connection = null;
    int count = 0;
    while (count < conf.getInt("jdbc.connection.retryCount", 10)) {
        try {/*from  www  .  ja  v  a2  s .c  om*/
            connection = ds.getConnection();
            if (connection != null) {
                if (isolation != null) {
                    connection.setTransactionIsolation(isolation.intValue());
                }
                if (connection.getAutoCommit() != autocommit) {
                    connection.setAutoCommit(autocommit);
                }
                log.debug("druid connection: " + connection.toString());
                return connection;
            } else {
                count++;
                try {
                    Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException ex) {
            count++;
            try {
                Thread.sleep(conf.getInt("jdbc.connection.retryTimeMs", 500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count >= conf.getInt("jdbc.connection.retryCount", 10)) {
                ex.printStackTrace();
                throw ex;
            }
        }
    }
    return connection;
}