List of usage examples for java.sql PreparedStatement executeQuery
ResultSet executeQuery() throws SQLException;
PreparedStatement
object and returns the ResultSet
object generated by the query. From source file:conexaoBanco.GerenciarProduto.java
public ArrayList getProdutos(Integer vendedor) { ArrayList produtos = new ArrayList(); if (con != null) { try {// w w w. j a va2s.co m PreparedStatement stmt = con .prepareStatement("SELECT * FROM produtos where vendedor = " + vendedor); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Produto produto = new Produto(); produto.setCodigo(rs.getInt("codigo")); produto.setNome(rs.getString("nome")); produto.setPreco(rs.getDouble("preco")); produto.setImagem(rs.getString("imagem")); produto.setDescricao(rs.getString("descricao")); produtos.add(produto); } } catch (Exception e) { e.printStackTrace(); } } return produtos; }
From source file:dao.DirectoryFileSearchQuery.java
/** * This method lists all the results for the search text from directories * @param conn the connection// w w w . j av a2 s .co m * @param collabrumId the collabrumid * @return HashSet the set that has the list of moderators for these collabrums. * @throws BaseDaoException - when error occurs **/ public HashSet run(Connection conn, String sString, String fileName, String dirName) throws BaseDaoException { //if ((RegexStrUtil.isNull(sString) || conn == null)) { if ((conn == null) || RegexStrUtil.isNull(fileName)) { return null; } //StringBuffer sb = new StringBuffer("select distinct d1.dirname, d2.directoryid, d2.entryid, d2.btitle from directory d1, dirblob d2 where"); StringBuffer sb = new StringBuffer( "select distinct d1.dirname, d2.directoryid, d2.entryid, d2.btitle from directory d1, dirblob d2 where"); if (!RegexStrUtil.isNull(sString)) { ArrayList columns = new ArrayList(); columns.add("dirname"); // set the sqlConstraint as " and " String sqlConstraint = " and "; sb.append(sqlSearch.getConstraint(columns, sString, sqlConstraint)); } else { sb.append("dirpath IS NULL"); } // directory name can be null if (!RegexStrUtil.isNull(dirName)) { sb.append(" and dirname like '%"); sb.append(dirName); sb.append("%'"); } sb.append(" and d1.directoryid=d2.directoryid and "); sb.append("d2.btitle like '%"); sb.append(fileName); sb.append("%'"); logger.info("sb.toString() = " + sb.toString()); try { PreparedStatement stmt = conn.prepareStatement(sb.toString()); ResultSet rs = stmt.executeQuery(); Vector columnNames = null; Directory directory = null; HashSet pendingSet = new HashSet(); if (rs != null) { columnNames = dbutils.getColumnNames(rs); } while (rs.next()) { directory = (Directory) eop.newObject(DbConstants.DIRECTORY); for (int j = 0; j < columnNames.size(); j++) { if (((String) (columnNames.elementAt(j))).equalsIgnoreCase(DbConstants.ENTRY_DATE)) { try { directory.setValue(DbConstants.ENTRY_DATE, GlobalConst.dncalendar.getDisplayDate(rs.getTimestamp(DbConstants.ENTRY_DATE))); } catch (ParseException e) { throw new BaseDaoException("could not parse the date for entrydate in directory " + rs.getTimestamp(DbConstants.ENTRY_DATE), e); } } else { directory.setValue((String) columnNames.elementAt(j), (String) rs.getString((String) columnNames.elementAt(j))); } } pendingSet.add(directory); } return pendingSet; } catch (Exception e) { throw new BaseDaoException("Error occured while executing search directory run query " + sb.toString(), e); } }
From source file:id.go.kemdikbud.tandajasa.dao.PegawaiDaoTest.java
@Test public void testHapus() throws Exception { DataSource ds = ctx.getBean(DataSource.class); Connection koneksiDatabase = ds.getConnection(); PreparedStatement ps = koneksiDatabase.prepareStatement("select count(*) as jumlah from pegawai"); ResultSet rsSebelum = ps.executeQuery(); Assert.assertTrue(rsSebelum.next()); Long jumlahRecordSebelum = rsSebelum.getLong(1); rsSebelum.close();/*from w w w . j a v a2 s .com*/ PegawaiDao pd = (PegawaiDao) ctx.getBean("pegawaiDao"); Pegawai p = pd.cariById(100); Assert.assertNotNull(p); pd.delete(p); ResultSet rsSetelah = ps.executeQuery(); Assert.assertTrue(rsSetelah.next()); Long jumlahRecordSetelah = rsSetelah.getLong("jumlah"); rsSetelah.close(); koneksiDatabase.close(); Assert.assertEquals(new Long(jumlahRecordSebelum - 1), new Long(jumlahRecordSetelah)); }
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 w ww . jav a2s . c om*/ 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:com.wso2telco.proxy.util.DBUtils.java
/** * Get a map of parameters mapped to a scope * * @return map of scope vs parameters/*www. 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; }
From source file:eagle.storage.jdbc.criteria.TestTorque.java
public void testSelect() throws TorqueException, SQLException { Criteria crit = new Criteria(); crit.setDbName("eagle"); crit.addSelectColumn(new ColumnImpl("column1")); crit.addSelectColumn(new ColumnImpl("column2")); crit.addSelectColumn(new ColumnImpl("column2/100")); crit.where(new ColumnImpl("column1"), SqlEnum.GREATER_EQUAL); crit.addFrom("tableName"); crit.addAlias("column1", "c1"); crit.addGroupByColumn(new ColumnImpl("column1")); crit.addAscendingOrderByColumn(new ColumnImpl("column3")); crit.setLimit(1000);/*from w w w . j av a 2s . co m*/ Query query = SqlBuilder.buildQuery(crit); String sql = query.toString(); System.out.println(sql); Connection connection = Torque.getConnection(); PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, 1000); try { ResultSet result = statement.executeQuery(); } catch (SQLException ex) { LOG.warn(ex.getMessage(), ex); } finally { connection.close(); } }
From source file:ece356.UserDBAO.java
public static String getSalt(String username) throws ClassNotFoundException, SQLException { Connection con = null;// w ww . ja va 2s.c o m PreparedStatement pstmt = null; UserData ret; try { con = getConnection(); String query = "select COUNT(*)as numRecords, password_salt from user INNER JOIN userType ON user.userTypeID = userType.userTypeID where user.username = ?"; pstmt = con.prepareStatement(query); pstmt.setString(1, username); ResultSet resultSet; resultSet = pstmt.executeQuery(); resultSet.next(); if (resultSet.getInt("numRecords") > 0) { return resultSet.getString("password_salt"); } else return null; } catch (Exception e) { System.out.println("EXCEPTION:%% " + e); } finally { if (pstmt != null) { pstmt.close(); } if (con != null) { con.close(); } } return null; }
From source file:com.imagelake.control.KeyWordsDAOImp.java
public JSONArray getJSONAllKeyWords() { JSONArray ja = new JSONArray(); try {/* ww w . ja va2s . c o m*/ String sql = "SELECT * FROM key_words GROUP BY key_word"; PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { JSONObject jo = new JSONObject(); jo.put("id", rs.getInt(1)); jo.put("kw", rs.getString(2)); ja.add(jo); } } catch (Exception e) { e.printStackTrace(); } return ja; }
From source file:io.kamax.mxisd.backend.sql.SqlThreePidProvider.java
@Override public List<_ThreePid> getThreepids(_MatrixID mxid) { List<_ThreePid> threepids = new ArrayList<>(); String stmtSql = cfg.getProfile().getThreepid().getQuery(); try (Connection conn = pool.get()) { PreparedStatement stmt = conn.prepareStatement(stmtSql); stmt.setString(1, mxid.getId()); ResultSet rSet = stmt.executeQuery(); while (rSet.next()) { String medium = rSet.getString("medium"); String address = rSet.getString("address"); threepids.add(new ThreePid(medium, address)); }//from www .j ava 2 s .c o m return threepids; } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:br.com.fatecpg.repositories.mysql.MySqlLogRepository.java
@Override public Log getById(int id) { if (id <= 0) { throw new IllegalArgumentException("id must be greather than 0."); }/* www .j av a 2 s. c om*/ Log log = null; String sql = "select id, applicationName, message, url, ipaddress, usernamme, createdon, details from log where id = ?"; Connection connection = dbProvider.getConnection(); try { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, id); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { log = new Log(); log.setId(resultSet.getInt("id")); log.setApplicationName(resultSet.getString("applicationName")); log.setMessage(resultSet.getString("message")); log.setUrl(resultSet.getString("url")); log.setIpAddress("ipaddress"); log.setUsername(resultSet.getString("username")); log.setCreatedDate(resultSet.getDate("createdOn")); log.setDetails(resultSet.getString("details")); } } catch (SQLException ex) { throw new RuntimeException(ex); } return log; }