i want to search the name who having skills in java and oracle
and i know the coding like
select name from table_name where skills like '%java%' or skills like '%oracle%';
but my problem is,In servlet How can i do this?
String skills=request.getParameter("skill");
my select query
select name from table_name where skill like '"++"';
Here i am confused ,
i tried like this
select name from table_name where skill like '"+%skills%+"';
but not working.
I am a webdeveloper very new to oracle ,please help me
I am using oracle10g
You may try REGEXP_LIKE
SELECT name from TABLENAME where
WHERE REGEXP_LIKE (skills, '(Java|Oracle)');
String query = "select name from table_name";
String skills = request.getParameter("skill");
StringBuilder likePart = new StringBuilder("");
boolean appendOrClause = false;
String skillsArray[] = skills == null ? null : skills.split(",");
if(skillsArray != null && skillsArray.length > 0 ){
for(String skill : skillsArray){
if(skill.trim().length() > 0){
if(appendOrClause){
likePart.append(" OR skills like '%" + skill.trim() + "%'");
} else {
likePart.append(" where skills like '%" + skill.trim() + "%'");
}
appendOrClause = true;
}
}
if(likePart.toString().trim().length() > 0){
query += likePart.toString();
}
}
if(query.indexOf("like") > 0 ){
// User have skills
// Fire query to get User Name
} else {
// User doesn't have any skills
// don't Fire any query
}
Related
I am building my sql string like this:
String sql = "SELECT * FROM horse WHERE 1=1 ";
if (horse.getName() != null) {
sql += "AND UPPER(name) LIKE ? ";
}
if (horse.getDescription() != null) {
sql += "AND UPPER(description) LIKE ? ";
}
if (horse.getRating() != null) {
sql += "AND rating=? ";
}
I want to find a match for entity depending on which parameters are passed. So if only name and rating are passed I would get something like: SELECT * FROM horse WHERE 1=1 AND UPPER(name) LIKE ? AND rating=?
Now I pass the sql string to query like this:
List<Horse> matchingHorses = jdbcTemplate.query(sql, new Object[]{horse.getName()}, mapHorse());
This returns a correct result but I have to pass to new Object[] {} only the parameters that I know that user is gonna pass or else I do not get anything. For example if user passes something like this:
{
"description":"desc"
}
I won't get any results even if there is a description with "desc". If I do this:
List<Horse> matchingHorses = jdbcTemplate.query(sql, new Object[]{horse.getName(), horse.getDescription(), horse.getRating()}, mapHorse());
and pass only name I get:
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [SELECT * FROM horse WHERE 1=1 AND UPPER(name) LIKE ? ];
Invalid value "2" for parameter "parameterIndex" [90008-200]; nested exception is org.h2.jdbc.JdbcSQLDataException: Invalid value "2" for parameter "parameterIndex" [90008-200]
Here is my mapHorse() row mapper:
private RowMapper<Horse> mapHorse() {
return (resultSet, i) -> {
Long horseId = resultSet.getLong("id");
String horseName = resultSet.getString("name");
String horseDesc = resultSet.getString("description");
int horseRating = resultSet.getInt("rating");
return new Horse(
horseId,
horseName,
horseDesc,
horseRating,
);
};
}
How do I implement this correctly?
You can use NamedParameterJdbcTemplate.
MapSqlParameterSource params = new MapSqlParameterSource();
if (horse.getName() != null) {
sql += "AND UPPER(name) LIKE :name ";
params.addValue("name", horse.getName());
}
if (horse.getDescription() != null) {
sql += "AND UPPER(description) LIKE :description ";
params.addValue("description", horse.getDescription());
}
if (horse.getRating() != null) {
sql += "AND rating=:rating ";
params.addValue("rating ", horse.getRating());
}
namedParameterJdbcTemplate.query(sql, params, mapHorse());
suggestion- better if you you use string builder.
I'm working on a simple VertX Application. I have a hsqlDB and I'm trying to execute a query where I want to get all IDs from the Table where the Name contains a search parameter
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE ?";
So this works when the Name is the same as the ?
When I try to use wildcards:
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE %?%";
or
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE '%?%'";
it doesn't work.
My Code:
private void getIDsBySearchString(String search, SQLConnection conn, Handler<AsyncResult<Vector<Integer>>> resultHandler) {
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE ?";
conn.queryWithParams(sql, new JsonArray().add(search), asyncResult -> {
if(asyncResult.failed()) {
resultHandler.handle(Future.failedFuture("No Names Found"));
} else {
int numRows = asyncResult.result().getNumRows();
if(numRows >= 1) {
Vector<Integer> IDVector = new Vector<>();
for(int i = 0; i < numRows; i++) {
int id = asyncResult.result().getRows().get(i).getInteger("ID");
IDVector.add(id);
}
resultHandler.handle(Future.succeededFuture(IDVector));
} else {
resultHandler.handle(Future.failedFuture("No Names found"));
}
}
});
}
How do I need to edit my query String so the ? will be replaced by the search String and I will be able to use wildcards?
A parameter cannot be inside a quoted string. It can be part of a concat expression involving other strings.
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE '%' || ? || '%'";
The part that should be changed is your search parameter, not the sql part:
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE ?";
conn.queryWithParams(sql, new JsonArray().add("%"+search+"%"), asyncResult -> { ... }
Can someone help me to have a look at what is wrong with my query?
Java code :
public boolean fValidLogin(String fUsername, String fPassword) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
String query = "SELECT fusername,fpassword FROM flogin WHERE fusername=" + fUsername + " AND fpassword=" + fPassword + "";
Query DBquery = session.createQuery(query);
for (Iterator it = DBquery.iterate(); it.hasNext();) {
it.next();
count++;
}
System.out.println("Total rows: " + count);
if (count == 1) {
return true;
} else {
return false;
}
}
MYSQL Code:
SELECT fusername,fpassword FROM flogin WHERE fusername="SAS" AND fpassword="Sas123"
Try this first:
"SELECT fusername,fpassword FROM flogin WHERE fusername=\"" + fUsername + "\" AND fpassword=\"" +fPassword +"\""
By the way you are tring to use a native query. Maybe you should consider to use "createNativeQuery" instead of "createQuery"
Your query is a victim of an SQL Injection, it can also cause syntax error, instead you have to use setParameter with a JPQL query :
String query = "SELECT f FROM flogin f WHERE f.fusername = ? AND f.fpassword = ?";
Query dBquery = session.createQuery(query);
dBquery.setParameter(0, fUsername);//set username variable
dBquery.setParameter(1, fPassword);//set password variable
To get the nbr of result you can just call Query::list()
int count = dBquery.list().size();
Or just :
return dBquery.list().size() == 1;
The real problem in your query is that the String should be between two quotes (but i don't advice with solution)
fusername='" + fUsername + "'
//--------^_________________^
Note: Your query is not a JPQL Query, it seems a native query, if that you have to use session.createNativeQuery(query);.
I need to write hibernate query (createSQLquery) in Java land
I have query but I bit lost how to create criteria for my query.
basically I have to transfer regular where clause to hibernate .add(Restriction)
for instance lets take:
where (name LIKE '%test%' or lastname LIKE '%test%') and (site_id = 2) and (date>=121212 and date <= 343343)
Query query = sess.createSQLQuery(sql).addScalar("ID", Hibernate.long);
query.add(Restrictions.or (
Restrictions.like("name", "%test%")
Restrictions.like("lastname", "Fritz%")
))
.add(Restrictions.eq("site_id", new Integer(2)))
.add(Restrictions.add(Restrictions.gr("date_start", 122122)
.add(Restrictions.le("date_end", 345433)));
I did not have chance to run it since do not have access to my environment now, just would love to figure out this.
Thanks
You have to do like this
Criteria criteria = session.createCriteria(YourPojo.class);
criteria.add(Restrictions.eq("id", id));
criteria .add(Restrictions.or (
Restrictions.like("name", "%test%"),
Restrictions.like("lastname", "Fritz%")));
criteria.add(Restrictions.eq("site_id", new Integer(2)))
criteria.add(Restrictions.add(Restrictions.gr("date_start", 122122)
.add(Restrictions.le("date_end", 345433)));
return (criteria.list());
okay, problem solved this way:
Query from XML - I put in where clause
<Applications>
<Application name="AlertData">
<Query name="alerts">
<SQL>
SELECT
mr.measurement_date as measurementDate,
........ // more data
FROM measurement m
LEFT JOIN tags ON mr.tag_id = tags.tag_id
.......... // more joins
WHERE
mr.site_id = :siteid
$searchConstraints$ // just a string
$dateStartFragment$ // just a string
</SQL>
</Query>
</Application>
</Applications>
Next Java code:
if (search != null && !search.isEmpty()) {
searchFragment = " AND (UPPER(field1) LIKE :search" +
" OR UPPER(field2) LIKE :search)";
}
sql = this.prepareQuery(sql, ImmutableMap.of(
"searchConstraints", searchFragment,
"dateStartFragment", dateStartFragment
));
Query query = this.sessionFactory.getCurrentSession()
.createSQLQuery(sql)
//more query here
if (search != null && !search.isEmpty()) {
query.setString("search", "%" + search.toUpperCase() + "%");
}
public String prepareQuery(String queryString, Map<String, String> templateVars) {
ST stringTemplater = new ST(queryString, '$', '$');
for (String key : templateVars.keySet()) {
stringTemplater.add(key, templateVars.get(key));
}
String renderedQuery = stringTemplater.render();
return renderedQuery;
}
I am trying to use a MapSqlParameterSource to create a query using a Like clause.
The code is something like this. The function containing it receives nameParam:
String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE :pname ";
String finalName= "'%" +nameParam.toLowerCase().trim() + "%'";
MapSqlParameterSource namedParams= new MapSqlParameterSource();
namedParams.addValue("pname", finalName);
int count= this.namedParamJdbcTemplate.queryForInt(namecount, namedParams);
This does not work correctly, giving me somewhere between 0-10 results when I should be receiving thousands. I essentially want the final query to look like:
SELECT count(*) FROM People WHERE LOWER(NAME) LIKE '%name%'
but this is evidently not happening. Any help would be appreciated.
Edit:
I have also tried putting the '%'s in the SQL, like
String finalName= nameParam.toLowerCase().trim();
String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE '%:pname%' "
;
but this does not work either.
You don't want the quotes around your finalName string. with the named parameters you don't need to specify them. This should work:
String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE :pname ";
String finalName= "%" + nameParam.toLowerCase().trim() + "%";
MapSqlParameterSource namedParams= new MapSqlParameterSource();
namedParams.addValue("pname", finalName);
int count= this.namedParamJdbcTemplate.queryForInt(namecount, namedParams);
This solution worked for me. I put the "%" on the Object[] parameters list:
String sqlCommand = "SELECT customer_id, customer_identifier_short, CONCAT(RTRIM(customer_identifier_a),' ', RTRIM(customer_identifier_b)) customerFullName "
+ " FROM Customer "
+ " WHERE customer_identifier_short LIKE ? OR customer_identifier_a LIKE ? "
+ " LIMIT 10";
List<Customer> customers = getJdbcTemplate().query(sqlCommand, new Object[] { query + "%", query + "%"}, new RowMapper<Customer>() {
public Customer mapRow(ResultSet rs, int i) throws SQLException {
Customer customer = new Customer();
customer.setCustomerFullName(rs.getString("customerFullName"));
customer.setCustomerIdentifier(rs.getString("customer_identifier_short"));
customer.setCustomerID(rs.getInt("customer_id"));
return customer;
}
});
return customers;
Have you tried placing the % wild cards in your sql string (not the bind variable value itself):
String finalName= nameParam.toLowerCase().trim();
String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE '%:finalName%'";
We can use simple JdbcTemplate instead of NamedParamJdbcTemplate
String namecount = "SELECT count(*) FROM People WHERE LOWER(NAME) LIKE ? ";
String finalName= "%" +nameParam.toLowerCase().trim() + "%"; //Notes: no quote
getJdbcTemplate().queryForInt(namecount, new Object[] {finalName});
Hope it helpful for someone using JdbcTemplate