Example usage for javax.sql DataSource getConnection

List of usage examples for javax.sql DataSource getConnection

Introduction

In this page you can find the example usage for javax.sql DataSource getConnection.

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Attempts to establish a connection with the data source that this DataSource object represents.

Usage

From source file:cz.jirutka.spring.data.jdbc.sql.SqlGeneratorFactory.java

/**
 * @param dataSource The DataSource for which to find compatible
 *        SQL Generator./*from w w w .j  av a 2 s  .com*/
 * @return An SQL Generator compatible with the given {@code dataSource}.
 * @throws DataAccessResourceFailureException if exception is thrown when
 *         trying to obtain Connection or MetaData from the
 *         {@code dataSource}.
 * @throws IllegalStateException if no compatible SQL Generator is found.
 */
public SqlGenerator getGenerator(DataSource dataSource) {

    if (cache.containsKey(dataSource)) {
        return cache.get(dataSource);
    }

    DatabaseMetaData metaData;
    try {
        metaData = dataSource.getConnection().getMetaData();
    } catch (SQLException ex) {
        throw new DataAccessResourceFailureException("Failed to retrieve database metadata", ex);
    }

    for (SqlGenerator generator : generators) {
        try {
            if (generator.isCompatible(metaData)) {
                LOG.info("Using SQL Generator {} for dataSource {}", generator.getClass().getName(),
                        dataSource.getClass());

                cache.put(dataSource, generator);
                return generator;
            }
        } catch (SQLException ex) {
            LOG.warn("Exception occurred when invoking isCompatible() on {}",
                    generator.getClass().getSimpleName(), ex);
        }
    }

    // This should not happen, because registry should always contain one
    // "default" generator that returns true for every DatabaseMetaData.
    throw new IllegalStateException("No compatible SQL Generator found.");
}

From source file:com.migratebird.database.IdentifierProcessorFactory.java

/**
 * Determines the case the database uses to store non-quoted identifiers. This will use the connections
 * database metadata to determine the correct case.
 *
 * @param customStoredIdentifierCase The stored case: possible values 'lower_case', 'upper_case', 'mixed_case' and 'auto'
 * @param dataSource                 The datas ource, not null
 * @return The stored case, not null//from  w ww .  ja  v  a2s .c  o m
 */
protected StoredIdentifierCase determineStoredIdentifierCase(StoredIdentifierCase customStoredIdentifierCase,
        DataSource dataSource) {
    if (customStoredIdentifierCase != null) {
        return customStoredIdentifierCase;
    }

    Connection connection = null;
    try {
        connection = dataSource.getConnection();

        DatabaseMetaData databaseMetaData = connection.getMetaData();
        if (databaseMetaData.storesUpperCaseIdentifiers()) {
            return UPPER_CASE;
        } else if (databaseMetaData.storesLowerCaseIdentifiers()) {
            return LOWER_CASE;
        } else {
            return MIXED_CASE;
        }
    } catch (SQLException e) {
        throw new DatabaseException("Unable to determine stored identifier case.", e);
    } finally {
        closeQuietly(connection, null, null);
    }
}

From source file:sf.wicklet.gwt.site.server.db.H2Configurator.java

@Override
public void shutdown(final DataSource datasource, final String dbname) {
    if (Config.DEBUG) {
        System.out.println("# Shutdown database: " + dbname);
    }/*from w  ww  .ja  v a  2  s .c om*/
    try {
        final Connection connection = datasource.getConnection();
        final Statement stmt = connection.createStatement();
        stmt.execute("SHUTDOWN");
    } catch (final SQLException ex) {
        Config.get().getLogger().warn("Could not shutdown embedded database", ex);
    }
}

From source file:com.sf.ddao.shards.conn.ShardedConnectionHandler.java

@Override
public Connection createConnection(Context context) throws SQLException {
    final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class);
    final ShardKeyGetter shardKeyGetter = shardKeyGetterMap.get(callCtx.getMethod());
    if (shardKeyGetter == null) {
        throw new ShardException(
                "Expected parameter with annotation " + ShardKey.class + " at method " + callCtx.getMethod());
    }//w w w  . j a  va2s  . co m
    Object shardKey = shardKeyGetter.getShardKey(callCtx.getArgs());
    try {
        @SuppressWarnings({ "unchecked" })
        DataSource ds = shardingService.getShard(shardKey, context);
        //noinspection SuspiciousMethodCalls
        return ds.getConnection();
    } catch (Exception e) {
        throw new SQLException("Failed to retrieve shard for key " + shardKey
                + (shardKey == null ? "" : "(" + shardKey.getClass() + ")"), e);
    }
}

From source file:com.migratebird.database.IdentifierProcessorFactory.java

/**
 * Determines the string used to quote identifiers to make them case-sensitive. This will use the connections
 * database metadata to determine the quote string.
 *
 * @param customIdentifierQuoteString If not null, it specifies a custom identifier quote string that replaces the one
 *                                    specified by the JDBC DatabaseMetaData object
 * @param dataSource                  The datas ource, not null
 * @return The quote string, null if quoting is not supported
 *///  w  ww .ja v  a 2  s.  c o  m
protected String determineIdentifierQuoteString(String customIdentifierQuoteString, DataSource dataSource) {
    if (customIdentifierQuoteString != null) {
        return trimToNull(customIdentifierQuoteString);
    }

    Connection connection = null;
    try {
        connection = dataSource.getConnection();

        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String quoteString = databaseMetaData.getIdentifierQuoteString();
        return trimToNull(quoteString);

    } catch (SQLException e) {
        throw new DatabaseException("Unable to determine identifier quote string.", e);
    } finally {
        closeQuietly(connection, null, null);
    }
}

From source file:org.biblionum.authentification.modele.UtilisateurModele.java

/**
 * Java method that inserts a row in the generated sql table and returns the
 * new generated id/*from  w w w  .  ja  va 2  s.  com*/
 *
 * @param con (open java.sql.Connection)
 * @param nom
 * @param password
 * @param pseudo
 * @param prenom
 * @param utilisateur_type_id
 * @return id (database row id [id])
 * @throws SQLException
 */
public int insertIntoUtilisateur(DataSource ds, String nom, String password, String pseudo, String prenom)
        throws SQLException {
    con = ds.getConnection();
    int generatedId = -1;
    String sql = "INSERT INTO utilisateur (nom, " + "password, pseudo, prenom)" + "VALUES (?, ?, ?, ?)";
    PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    statement.setString(1, nom);
    statement.setString(2, password);
    statement.setString(3, pseudo);
    statement.setString(4, prenom);

    statement.execute();
    ResultSet auto = statement.getGeneratedKeys();

    if (auto.next()) {
        generatedId = auto.getInt(1);
    } else {
        generatedId = -1;
    }

    statement.close();
    con.close();
    return generatedId;
}

From source file:com.micromux.cassandra.jdbc.PooledTest.java

@Test
public void twoMillionPreparedStatements() throws Exception {
    CassandraDataSource connectionPoolDataSource = new CassandraDataSource(HOST, PORT, KEYSPACE, USER, PASSWORD,
            VERSION, CONSISTENCY, TRUST_STORE, TRUST_PASS);

    DataSource pooledCassandraDataSource = new PooledCassandraDataSource(connectionPoolDataSource);

    Connection connection = pooledCassandraDataSource.getConnection();
    for (int i = 0; i < 10000; i++) {
        PreparedStatement preparedStatement = connection
                .prepareStatement("SELECT someInt FROM pooled_test WHERE somekey = ?");
        preparedStatement.close();/* ww  w  . j  av a2 s  .  c o m*/
    }
    connection.close();
}

From source file:de.langmi.spring.batch.examples.readers.support.CompositeCursorItemReaderTest.java

/**
 * Create a table and fill with some test data.
 *
 * @param dataSource/*w  ww. ja va 2  s  . c o  m*/
 * @throws Exception 
 */
private void createTableWithTestData(final DataSource dataSource) throws Exception {
    // create table
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute(CREATE_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // fill with values
    conn = dataSource.getConnection();
    // prevent auto commit for batching
    conn.setAutoCommit(false);
    PreparedStatement ps = conn.prepareStatement(INSERT);
    // fill with values
    for (int i = 0; i < EXPECTED_COUNT; i++) {
        ps.setString(1, String.valueOf(i));
        ps.addBatch();
    }
    ps.executeBatch();
    conn.commit();
    ps.close();
    conn.close();
}

From source file:com.micromux.cassandra.jdbc.PooledTest.java

@Test
public void statement() throws Exception {
    CassandraDataSource connectionPoolDataSource = new CassandraDataSource(HOST, PORT, KEYSPACE, USER, PASSWORD,
            VERSION, CONSISTENCY, TRUST_STORE, TRUST_PASS);

    DataSource pooledCassandraDataSource = new PooledCassandraDataSource(connectionPoolDataSource);

    Connection connection = pooledCassandraDataSource.getConnection();

    Statement statement = connection.createStatement();

    ResultSet resultSet = statement.executeQuery("SELECT someInt FROM pooled_test WHERE somekey = 'world'");
    assertTrue(resultSet.next());//from www  .  j a  v a  2  s  . co  m
    assertEquals(1, resultSet.getInt(1));
    assertFalse(resultSet.next());
    resultSet.close();

    statement.close();
    connection.close();
}

From source file:Controllers.AppointmentController.java

/**
 * Return list of all departments from db.
 *
 * @return//from   w w  w  . j av  a 2  s.  c  om
 */
public Department[] fetchDepartments() {

    Department[] dep = null;

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        Statement stmt = connection.createStatement();

        String smtquery = "SELECT * FROM departments";
        ResultSet resultSet;
        resultSet = stmt.executeQuery(smtquery);

        List<Department> departments = new ArrayList<Department>();
        while (resultSet.next()) {
            Department department = new Department();
            department.setDepartmentId(resultSet.getInt("departmentId"));
            department.setDepartmentName(resultSet.getString("departmentName"));
            departments.add(department);
        }

        dep = new Department[departments.size()];
        dep = departments.toArray(dep);

        stmt.close();

    } catch (NamingException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return dep;
}