Example usage for java.sql PreparedStatement setString

List of usage examples for java.sql PreparedStatement setString

Introduction

In this page you can find the example usage for java.sql PreparedStatement setString.

Prototype

void setString(int parameterIndex, String x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java String value.

Usage

From source file:dk.netarkivet.common.utils.DBUtils.java

/** Returns the version of a table according to schemaversions, or 0
 * for the initial, unnumbered version./*from   w  ww. java2 s.co  m*/
 *
 * NB: the provided connection is not closed
 *
 * @param connection connection to the database.
 * @param tablename The name of a table in the database.
 * @return Version of the given table.
 * @throws IOFailure if DB table schemaversions does not exist
 */
public static int getTableVersion(Connection connection, String tablename) throws IOFailure {
    ArgumentNotValid.checkNotNull(connection, "Connection connection");
    ArgumentNotValid.checkNotNullOrEmpty(tablename, "String tablenname");
    PreparedStatement s = null;
    int version = 0;
    try {
        s = connection.prepareStatement("SELECT version FROM schemaversions" + " WHERE tablename = ?");
        s.setString(1, tablename);
        ResultSet res = s.executeQuery();
        if (!res.next()) {
            log.warn("As yet unknown tablename '" + tablename + "' in table schemaversions. The table"
                    + " should be automatically created in the database " + "when it is first needed.");
        } else {
            version = res.getInt(1);
            if (res.wasNull()) {
                log.warn("Null table version for '" + tablename + "'");
            }
        }
        return version;
    } catch (SQLException e) {
        String msg = "SQL Error checking version of table " + tablename + "\n"
                + ExceptionUtils.getSQLExceptionCause(e);
        log.warn(msg, e);
        throw new IOFailure(msg, e);
    } finally {
        closeStatementIfOpen(s);
    }
}

From source file:com.vionto.vithesaurus.BaseformFinder.java

public Set<String> getBaseForms(Connection connection, String term) throws SQLException {
    final List<String> parts = new ArrayList<String>(splitter.splitWord(term));
    final String searchTerm;
    if (parts.size() > 0) {
        searchTerm = parts.get(parts.size() - 1);
    } else {//from ww w . j a v a2s  .c  o  m
        searchTerm = term;
    }
    final Set<String> baseforms = new HashSet<String>();
    final String sql = "SELECT baseform FROM word_mapping WHERE fullform = ?";
    final PreparedStatement statement = connection.prepareStatement(sql);
    try {
        statement.setString(1, searchTerm);
        final ResultSet resultSet = statement.executeQuery();
        try {
            while (resultSet.next()) {
                final String baseform;
                if (parts.size() > 1) {
                    baseform = joinAllButLast(parts, resultSet.getString("baseform"));
                } else {
                    baseform = resultSet.getString("baseform");
                }
                baseforms.add(baseform);
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
    return baseforms;
}

From source file:image.JdbcInsertFileOne.java

public void enregistrer(String path, String type, Voiture voiture, String numPac) {

    String url = "jdbc:mysql://localhost:3306/loc_voiture_db";
    String user = "root";
    String password = "";

    String filePath = path;/*ww  w .jav  a 2 s.  c o  m*/
    List<Parc> parcs = metier.listerParc();

    for (Iterator<Parc> iterator = parcs.iterator(); iterator.hasNext();) {
        Parc next = iterator.next();
        if (next.getNumParc().equals(numPac)) {
            idParc = next.getIdPac();
            break;
        }
    }

    try {
        Connection conn = DriverManager.getConnection(url, user, password);

        String sql = "INSERT INTO `voiture` (`immatriculation_voiture`,"
                + " `marque_voiture`, `modele_voiture`, `categorie_voiture`, `couleur_voiture`, "
                + "`carburant_voiture`, `boite_vitesse_voiture`, `climatisation_voiture`, "
                + "`nbr_portes_voiture`, `nbr_places_voiture`, `type_voiture`, `etat_voiture`, "
                + "`id_pac_voiture`, `annee_mise_service`, `type`,`image`, `prix_par_jour_3jour`,"
                + " `prix_par_jour_1semaine`)" + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, voiture.getImmatriculationVoiture());
        statement.setString(2, voiture.getMarqueVoiture());
        statement.setString(3, voiture.getModeleVoiture());
        statement.setString(4, voiture.getCategorieVoiture());
        statement.setString(5, voiture.getCouleurVoiture());
        statement.setString(6, voiture.getCarburantVoiture());
        statement.setString(7, voiture.getBoiteVitesseVoiture());

        statement.setString(8, voiture.getClimatisationVoiture());
        statement.setInt(9, voiture.getNbrPortesVoiture());
        statement.setInt(10, voiture.getNbrPortesVoiture());
        statement.setString(11, voiture.getTypeVoiture());
        statement.setString(12, voiture.getEtatVoiture());
        statement.setInt(13, idParc);
        statement.setString(14, voiture.getAnneeMiseService());
        statement.setString(15, type);

        InputStream inputStream = new FileInputStream(new File(filePath));

        statement.setBlob(16, inputStream);
        statement.setString(17, voiture.getPrixParJour3jour());
        statement.setString(18, voiture.getPrixParJour1semaine());

        int row = statement.executeUpdate();
        if (row > 0) {
            System.out.println("A contact was inserted with photo image.");
        }
        conn.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.rajaram.bookmark.dao.BookmarkDaoImpl.java

@Override
public List<Bookmark> getBookmarks(String userName) {

    String sql = "select * from " + tableName + " where user_name = ?";

    Connection conn = null;//ww w.  j a  va 2  s. c  om
    BookmarkRowMapper rowExtract = new BookmarkRowMapper();
    List<Bookmark> bookmarks = null;

    try {
        conn = dataSource.getConnection();
        PreparedStatement prepareStatement = conn.prepareStatement(sql);
        prepareStatement.setString(1, userName);
        ResultSet rs = prepareStatement.executeQuery();

        bookmarks = rowExtract.mapRow(rs);

        rs.close();
        prepareStatement.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }

    return bookmarks;
}

From source file:dao.MaterialDaoImplem.java

@Override
public boolean updateMaterial(Material material) {
    try (Connection connection = dataSource.getConnection()) {
        String query = ("update Material m "
                + "set m.name=?, m.weight=?, m.manufacturer=?,m.cost=?,m.quantity=? WHERE m.id_material=?");
        PreparedStatement stat = connection.prepareStatement(query);
        stat.setString(1, material.getName());
        stat.setInt(2, material.getWeight());
        stat.setString(3, material.getManufacturer());
        stat.setInt(4, material.getCost());
        stat.setInt(5, material.getQuantity());
        stat.setInt(6, material.getId_material());
        stat.execute();//  ww w.  j  a va 2 s  . co m
        return true;
    } catch (Exception e) {
        throw new RuntimeException("Error:updateMaterial", e);
    }
}

From source file:com.uit.anonymousidentity.Repository.IssuerKeys.IssuerJDBCTemplate.java

@Override
public void store(Issuer issuer) throws SQLException {
    String t_sql = "insert into %s (%s, %s, %s, %s) values ( ?, ?, ?, ? )";
    String sql = String.format(t_sql, TABLE_NAME, SID, BNCurveName, PK, SK);
    PreparedStatement pst = dataSource.getConnection().prepareStatement(sql);
    pst.setString(1, issuer.getSid());
    pst.setString(2, issuer.getCurve().getName());
    pst.setString(3, issuer.pk.toJSON(issuer.getCurve()));
    pst.setString(4, issuer.getSk().toJson(issuer.getCurve()));
    pst.executeUpdate();/*from   w w  w.  j  a v a  2s .co  m*/
    pst.close();

}

From source file:com.unito.model.repository.TableRepository.java

public int saveTable(Table tableToSave) {
    System.out.println("saving");
    KeyHolder keyHolder = new GeneratedKeyHolder();
    System.out.println(keyHolder.getKey());
    //http://docs.spring.io/spring/docs/2.5.x/reference/jdbc.html#jdbc-auto-genereted-keys
    jdbcTemplate.update(new PreparedStatementCreator() {
        @Override/*w  w  w. j  a va 2 s.c  om*/
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(INSERT_TABLE, new String[] { "id" });
            ps.setString(1, tableToSave.getName());
            ps.setString(2, tableToSave.getOwner());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue() >= 0 ? keyHolder.getKey().intValue() : -1;
}

From source file:oobbit.orm.Categories.java

public Category getOne(String id) throws SQLException, NothingWasFoundException {
    PreparedStatement statement = getConnection()
            .prepareStatement("SELECT * FROM categories WHERE category_id = ?;");
    statement.setString(1, id);

    ResultSet query = statement.executeQuery();

    if (query.next()) {
        Category category = new Category();
        category.parse(query);/*from   w  w w .  j a v a 2s  . co  m*/
        return category;
    } else {
        throw new NothingWasFoundException("No such category!");
    }
}

From source file:com.sourcesense.maven.dbdep.plugin.dao.DbDependenciesDao.java

/**
 * /* www.  j  ava2 s  .c  o m*/
 * @param dependency
 * @return TRUE if dependency exist
 */
private boolean existDependency(final DependencyDO dependency) {
    Boolean result = new Boolean(false);
    try {
        result = (Boolean) this.jdbcTemplate.query(psSelect, new PreparedStatementSetter() {
            public void setValues(java.sql.PreparedStatement ps) throws java.sql.SQLException {
                ps.setString(1, dependency.getProject());
                ps.setString(2, dependency.getEnvironment());
                ps.setString(3, dependency.getName());
                ps.setString(4, dependency.getVersion());
            };
        }, new ResultSetExtractor() {
            public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
                if (rs != null && rs.next())
                    return new Boolean(true);
                else
                    return new Boolean(false);
            }
        });
    } catch (DataAccessException e) {
        log.error("Error during checking this dependency: " + dependency, e);
        throw new RuntimeException("Error during checking this dependency: " + dependency, e);
    }

    return result.booleanValue();
}

From source file:com.wso2telco.proxy.util.DBUtils.java

/**
 * Get a map of parameters mapped to a scope
 *
 * @return map of scope vs parameters//from ww w  .  j a  v  a  2 s  .  c o m
 * @throws AuthenticatorException on errors
 */
public static Map<String, ScopeParam> getScopeParams(String scope) throws AuthenticatorException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet results = null;
    String[] scopeValues = scope.split("\\s+|\\+");
    StringBuilder params = new StringBuilder("?");
    for (int i = 1; i < scopeValues.length; i++) {
        params.append(",?");
    }
    String sql = "SELECT * FROM `scope_parameter` WHERE scope in (" + params + ")";

    if (log.isDebugEnabled()) {
        log.debug("Executing the query " + sql);
    }

    Map scopeParamsMap = new HashMap();
    try {
        conn = getConnectDBConnection();
        ps = conn.prepareStatement(sql);
        for (int i = 0; i < scopeValues.length; i++) {
            ps.setString(i + 1, scopeValues[i]);
        }
        results = ps.executeQuery();

        Boolean mainScopeFound = false;
        List<String> scopeValuesFromDatabase = new ArrayList<>();

        while (results.next()) {
            Boolean isMultiscope = results.getBoolean("is_multiscope");
            scopeValuesFromDatabase.add(results.getString("scope"));

            if (!isMultiscope) {
                //throw error if multiple main scopes found
                if (mainScopeFound) {
                    throw new ConfigurationException("Multiple main scopes found");
                }

                //mark as main scope found
                mainScopeFound = true;

                scopeParamsMap.put("scope", results.getString("scope"));

                ScopeParam parameters = new ScopeParam();
                parameters.setScope(results.getString("scope"));
                parameters.setLoginHintMandatory(results.getBoolean("is_login_hint_mandatory"));
                parameters.setHeaderMsisdnMandatory(results.getBoolean("is_header_msisdn_mandatory"));
                parameters.setMsisdnMismatchResult(ScopeParam.msisdnMismatchResultTypes
                        .valueOf(results.getString("msisdn_mismatch_result")));
                parameters.setHeFailureResult(
                        ScopeParam.heFailureResults.valueOf(results.getString("he_failure_result")));
                parameters.setTncVisible(results.getBoolean("is_tnc_visible"));
                parameters.setLoginHintFormat(getLoginHintFormatTypeDetails(results.getInt("param_id"), conn));

                scopeParamsMap.put("params", parameters);
            }
        }

        //validate all scopes and compare with scopes fetched from database
        for (String scopeToValidate : scopeValues) {
            if (!scopeValuesFromDatabase.contains(scopeToValidate)) {
                throw new ConfigurationException("One or more scopes are not valid");
            }
        }
    } catch (SQLException e) {
        handleException("Error occurred while getting scope parameters from the database", e);
    } catch (ConfigurationException e) {
        handleException(e.getMessage(), e);
    } catch (NamingException e) {
        log.error("Naming exception ", e);
    } finally {
        closeAllConnections(ps, conn, results);
    }
    return scopeParamsMap;
}