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:fll.web.admin.ChangePassword.java

public static void populateContext(final HttpServletRequest request, final ServletContext application,
        final PageContext pageContext) {

    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {//w  w w  .j av  a  2s  .  c o m
        connection = datasource.getConnection();

        final Collection<String> loginKeys = CookieUtils.findLoginKey(request);
        final String user = Queries.checkValidLogin(connection, loginKeys);
        pageContext.setAttribute("fll_user", user);

    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(connection);
    }

}

From source file:org.biblionum.commentaire.modele.CommentaireOuvragesModele.java

/**
 * Java method that deletes a row from the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param keyId (the primary key to the row)
 * @throws SQLException//ww  w . j ava 2  s  . com
 */
public static void deleteFromOuvragetype(DataSource ds, int keyId) throws SQLException {
    Connection con = ds.getConnection();
    String sql = "DELETE FROM ouvragetype WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql);
    statement.setInt(1, keyId);
    statement.executeUpdate();
    statement.close();
    con.close();
}

From source file:com.laudandjolynn.mytv.datasource.DataSourceManager.java

/**
 * ???//  w  w  w .j ava  2  s.  com
 * 
 * @return
 * @throws SQLException
 */
public static Connection getConnection() throws SQLException {
    if (dsClass == null) {
        throw new MyTvException("load db driver class error.");
    }

    try {
        if (Config.getDbType() == DbType.SQLITE) {
            return dsClass.newInstance().getConnection(DATA_SOURCE_PROP);
        }

        DataSource ds = BasicDataSourceFactory.createDataSource(DBCP_PROP);
        Connection conn = ds.getConnection();
        return conn;
    } catch (InstantiationException e) {
        throw new MyTvException("can't instantce db driver: " + dsClass, e);
    } catch (IllegalAccessException e) {
        throw new MyTvException(e);
    } catch (Exception e) {
        throw new MyTvException(e);
    }
}

From source file:org.biblionum.ouvrage.modele.CategorieOuvrageModele.java

/**
 * Java method that updates a row in the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param designation_categorie//w  ww . ja v a 2 s  .  c  o  m
 * @return boolean (true on success)
 * @throws SQLException
 */
public static boolean updateCategorieouvrage(DataSource ds, int keyId, String designation_categorie)
        throws SQLException {
    con = ds.getConnection();
    String sql = "SELECT * FROM categorieouvrage WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    statement.setInt(1, keyId);
    ResultSet entry = statement.executeQuery();

    entry.last();
    int rows = entry.getRow();
    entry.beforeFirst();
    if (rows == 0) {
        entry.close();
        statement.close();
        con.close();
        return false;
    }
    entry.next();

    if (designation_categorie != null) {
        entry.updateString("designation_categorie", designation_categorie);
    }

    entry.updateRow();
    entry.close();
    statement.close();
    con.close();
    return true;
}

From source file:com.dangdang.ddframe.rdb.sharding.example.jdbc.Main.java

private static void printGroupBy(final DataSource dataSource) throws SQLException {
    String sql = "SELECT o.user_id, COUNT(*) FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id GROUP BY o.user_id";
    try (Connection conn = dataSource.getConnection();
            PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
            System.out.println("user_id: " + rs.getInt(1) + ", count: " + rs.getInt(2));
        }//from  w w w  .j  a v a  2s. c o  m
    }
}

From source file:com.dangdang.ddframe.rdb.sharding.example.jdbc.Main.java

private static void printSimpleSelect(final DataSource dataSource) throws SQLException {
    String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";
    try (Connection conn = dataSource.getConnection();
            PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
        preparedStatement.setInt(1, 10);
        preparedStatement.setInt(2, 1001);
        try (ResultSet rs = preparedStatement.executeQuery()) {
            while (rs.next()) {
                System.out.println(rs.getInt(1));
                System.out.println(rs.getInt(2));
                System.out.println(rs.getInt(3));
            }/*from  w  ww  .j  ava2 s  .com*/
        }
    }
}

From source file:org.biblionum.ouvrage.modele.CategorieOuvrageModele.java

/**
 * get all categorie/*from ww  w . ja v a2  s. co m*/
 */
public static ArrayList<CategorieOuvrage> getCategorieOuvrage(DataSource ds) {

    ArrayList<CategorieOuvrage> list = new ArrayList<CategorieOuvrage>();

    try {
        con = ds.getConnection();
        stm = con.prepareStatement("SELECT * FROM categorieouvrage");

        rs = stm.executeQuery();

        BeanProcessor bp = new BeanProcessor();
        list = (ArrayList) bp.toBeanList(rs, CategorieOuvrage.class);

        con.close();
        rs.close();

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

    return list;
}

From source file:org.bibsonomy.database.common.util.AbstractDatabaseSchemaInformation.java

/**
 * returns meta informations of the database
 * /*  w  ww.  j a  v  a  2  s .c  om*/
 * @param <R>
 * @param resultClass
 * @param tableNamePattern
 * @param columnNamePattern
 * @param columnLabel
 * 
 * @return the schema information of the column of the table
 */
@SuppressWarnings("unchecked")
protected static <R> R getSchemaInformation(/* only used for the cast */final Class<R> resultClass,
        final String tableNamePattern, final String columnNamePattern, final String columnLabel,
        final SqlMapSession sqlMapSession) {
    final DataSource dataSource = sqlMapSession.getDataSource();

    Connection connection = null;

    try {
        connection = dataSource.getConnection();
        final DatabaseMetaData metaData = connection.getMetaData();
        final ResultSet columns = metaData.getColumns(null, null, tableNamePattern, columnNamePattern);
        while (columns.next()) {
            return (R) columns.getObject(columnLabel);
        }
    } catch (final SQLException ex) {
        log.warn("can't get schema informations for column '" + columnNamePattern + "' of table '"
                + tableNamePattern + "'", ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (final SQLException ex) {
                log.warn("can't close connection", ex);
            }
        }
    }

    return null;
}

From source file:com.alibaba.druid.pool.bonecp.TestLRU.java

public static void f(DataSource ds, int count) throws Exception {
    Connection[] connections = new Connection[count];
    for (int i = 0; i < count; ++i) {
        connections[i] = ds.getConnection();
    }/*  w ww  . j  a v  a  2  s .com*/

    for (int i = 0; i < count; ++i) {
        System.out.println(unwrap(connections[i]).getId());
    }

    for (int i = count - 1; i >= 0; --i) {
        connections[i].close();
    }
}

From source file:com.funambol.pushlistener.util.DBHelper.java

/**
 *
 * A connection taken from the core datasource.
 *
 * @return a jdbc connection.//from  w  w w  .j  av  a2s  .  c o m
 *
 * @throws java.lang.Exception if any error occurs.
 */
public static Connection getCoreConnection() throws Exception {
    DataSource ds = DataSourceTools.lookupDataSource(RegistryDao.DEFAULT_DATASOURCE_JNDI_NAME);
    Connection conn = null;
    try {
        conn = ds.getConnection();
        return conn;
    } catch (Exception e) {
        DBTools.close(conn, null, null);
        throw new Exception("An error occurred while obtaining core connection.", e);
    }
}