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:common.DBHelper.java

public static void executeSqlScript(DataSource ds, URL scriptUrl) throws SQLException {

    try (Connection conn = ds.getConnection()) {

        for (String sqlStatement : readSqlStatements(scriptUrl)) {
            if (!sqlStatement.trim().isEmpty()) {
                conn.prepareStatement(sqlStatement).executeUpdate();
            }// w w  w  .java  2 s  .c o m
        }
    }
}

From source file:common.DBHelper.java

/**
 * Executes SQL script./*from  w  w w .  java  2 s . co m*/
 *
 * @param ds datasource
 * @param is sql script to be executed
 * @throws SQLException when operation fails
 */
public static void executeSqlScript(DataSource ds, InputStream is) throws SQLException {
    try (Connection conn = ds.getConnection()) {
        for (String sqlStatement : readSqlStatements(is)) {
            if (!sqlStatement.trim().isEmpty()) {
                try (PreparedStatement preparedStatement = conn.prepareStatement(sqlStatement)) {
                    preparedStatement.executeUpdate();
                }
            }
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.RDFServiceSetup.java

public static Store connectStore(DataSource bds, StoreDesc storeDesc) throws SQLException {
    SDBConnection conn = new SDBConnection(bds.getConnection());
    return SDBFactory.connectStore(conn, storeDesc);
}

From source file:org.red5.server.plugin.admin.dao.UserDAO.java

public static UserDetails getUser(String username) {
    UserDetails details = null;//from ww w.  ja  v  a  2s. c o  m
    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        // JDBC stuff
        DataSource ds = UserDatabase.getDataSource();

        conn = ds.getConnection();
        //make a statement
        stmt = conn.prepareStatement("SELECT * FROM APPUSER WHERE username = ?");
        stmt.setString(1, username);
        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            log.debug("User found");
            details = new UserDetails();
            details.setEnabled("enabled".equals(rs.getString("enabled")));
            details.setPassword(rs.getString("password"));
            details.setUserid(rs.getInt("userid"));
            details.setUsername(rs.getString("username"));
            //
            rs.close();
            //get role            
            stmt = conn.prepareStatement("SELECT authority FROM APPROLE WHERE username = ?");
            stmt.setString(1, username);
            rs = stmt.executeQuery();
            if (rs.next()) {
                Collection<? extends GrantedAuthority> authorities;
                //                  authorities.addAll((Collection<?>) new GrantedAuthorityImpl(rs.getString("authority")));
                //                  details.setAuthorities(authorities);
                //
                //if (daoAuthenticationProvider != null) {
                //User usr = new User(username, details.getPassword(), true, true, true, true, authorities);
                //daoAuthenticationProvider.getUserCache().putUserInCache(usr);               
                //}
            }
        }
        rs.close();
    } catch (Exception e) {
        log.error("Error connecting to db", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
    return details;
}

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

/**
 * Java method that inserts a row in the generated sql table and returns the
 * new generated id//from w w  w . j  a  va  2s  . com
 *
 * @param con (open java.sql.Connection)
 * @param designation_categorie
 * @return id (database row id [id])
 * @throws SQLException
 */
public static int insertIntoCategorieouvrage(DataSource ds, String designation_categorie) throws SQLException {

    con = ds.getConnection();
    int generatedId = -1;
    String sql = "INSERT INTO categorieouvrage (designation_categorie)" + "VALUES (?)";
    PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    statement.setString(1, designation_categorie);
    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.qualogy.qafe.business.resource.rdb.query.enhancer.EnhancementManager.java

public static QueryContainer enhance(QueryContainer container, RDBDatasource dsResource) {
    if ((dsResource == null) || (dsResource.getDataSource() == null)) {
        throw new IllegalArgumentException(
                "Properties not read correctly or properties are incorrect, loading datasource failed");
    }//ww  w . j  a  v a  2 s  .com

    DataSource dataSource = dsResource.getDataSource();

    Connection con = null;

    try {
        con = dataSource.getConnection();

        DatabaseMetaData md = con.getMetaData();

        for (Iterator<Query> iter = container.values().iterator(); iter.hasNext();) {
            Query query = (Query) iter.next();

            if (query instanceof Batch) {
                for (Iterator<Query> iterator = ((Batch) query).getQueries().iterator(); iterator.hasNext();) {
                    Query batchQuery = (Query) iterator.next();
                    batchQuery = enhance(batchQuery, container, md);
                }
            } else {
                query = enhance(query, container, md);
            }

            container.update(query);
        }
    } catch (SQLException e) {
        String error = e.getMessage() + "[ on source ]" + dsResource.toString();
        throw new EnhancementFailedException(error);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                String error = e.getMessage() + "[ on source ]" + dsResource.toString();
                throw new EnhancementFailedException(error);
            }
        }
    }

    return container;
}

From source file:org.culturegraph.mf.sql.util.JdbcUtil.java

public static Connection getConnection(final String datasourceName) {
    try {/* w ww  . j ava 2s  .co m*/
        final InitialContext ctx = new InitialContext();
        final DataSource datasource = (DataSource) ctx.lookup(datasourceName);
        return datasource.getConnection();
    } catch (final NamingException ne) {
        throw new MetafactureException(ne);
    } catch (final SQLException se) {
        throw new MetafactureException(se);
    }
}

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

/**
 * Java method that creates the generated table
 *
 * @param con (open java.sql.Connection)
 * @throws SQLException/*from  w ww . j  a v  a2s.  c  om*/
 */
public static boolean createTableOuvragetype(DataSource ds) throws SQLException {
    Connection con = ds.getConnection();
    Statement statement = con.createStatement();
    String sql = "CREATE TABLE ouvragetype(id int AUTO_INCREMENT, " + "`contenu_commentaire` VARCHAR(255), "
            + "`date_commentaire` VARCHAR(255), " + "`utilisateurid` INT, " + "`ouvrageid` INT,)";
    statement.execute(sql);
    statement.close();
    con.close();
    return true;
}

From source file:com.gs.obevo.db.impl.platforms.sybasease.SybaseAseDeployerMainIT.java

public static void validateStep1(DataSource ds, JdbcHelper jdbc) throws Exception {
    List<Map<String, Object>> results;
    Connection conn = ds.getConnection();
    try {//w  w  w  . ja v  a2 s.  co m
        results = jdbc.queryForList(conn, "select * from TestTable order by idField");
    } finally {
        DbUtils.closeQuietly(conn);
    }

    assertEquals(4, results.size());
    validateResultRow(results.get(0), 1, "str1", 0);
    validateResultRow(results.get(1), 2, "str2", 0);
    validateResultRow(results.get(2), 3, "str3", 0);
    validateResultRow(results.get(3), 4, "str4", 0);
}

From source file:com.gs.obevo.db.impl.platforms.sybasease.SybaseAseDeployerMainIT.java

public static void validateStep2(DataSource ds, JdbcHelper jdbc) throws Exception {
    List<Map<String, Object>> results;
    Connection conn = ds.getConnection();
    try {/* w  w  w. j ava 2 s  . c o  m*/
        results = jdbc.queryForList(conn, "select * from TestTable order by idField");
    } finally {
        DbUtils.closeQuietly(conn);
    }

    assertEquals(5, results.size());
    validateResultRow(results.get(0), 1, "str1", 0);
    validateResultRow(results.get(1), 3, "str3Changed", 0);
    validateResultRow(results.get(2), 4, "str4", 0);
    validateResultRow(results.get(3), 5, "str5", 0);
    validateResultRow(results.get(4), 6, "str6", 0);
}