Reputation: 49
I am working on a Java-based desktop application with MySQL as my back end. In this application there is section called 'Search' where four fields are there - Key Skills (text field), Experience (combo box), City (combo box) and Notice Period (combo box). All the four field's value will be provided at run time. The key skills are comma separated values. I want a MySQL query using LIKE operator, with the help of which I don't have to provide comma separated values every time in the Key Skills text field. I just provide one value at run time and based on that value the query will fetch me the results using LIKE operator. My query is shown below
I have used placeholder '?' since my query is dynamic type. Is it possible to use placeholder in LIKE operator or does it only work with static type query?
String query = "SELECT F_Name, L_Name, Experience, Key_Skills,
FROM Candidate cd
JOIN Candidate2 cd2 ON(cd.Mobile = cd2.C_Mobile)
WHERE Key_Skills LIKE '%?%'";
When I executed the above query it produced an error stating - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version server version for the right syntax to use near 'FROM Candidate cd JOIN Candidate2 cd2 ON(cd.Mobile = cd2.C_Mobile) WHERE Key_Skills' at line 1
Upvotes: 4
Views: 7451
Reputation: 133360
Using concat you can build the like
string in a simple way for managing param value:
String query = "SELECT F_Name, L_Name, Experience, Key_Skills
FROM Candidate cd
JOIN Candidate2 cd2 ON(cd.Mobile = cd2.C_Mobile)
WHERE Key_Skills LIKE concat('%' , ?, '%')";
NB you have a wrong comma in key_Skills, FROM
- you must remove it.
It could be you have ambiguous column so I have updated the answer with a fully-qualified syntax.
String query = "SELECT
cd.F_Name
, cd.L_Name
, cd.Experience
, cd.Key_Skills
FROM Candidate cd
INNER JOIN Candidate2 cd2 ON cd.Mobile = cd2.C_Mobile
WHERE cd.Key_Skills LIKE concat('%' , ?, '%')";
Upvotes: 2
Reputation: 109547
You can do the prefix and suffix in the Java code instead of concatenating them in SQL.
WHERE Key_Skills LIKE ?";
Maybe even allowing wild cards:
keySkills = keySkills.replace('*', '%');
keySkills = keySkills.replace('?', '_');
preparedStatement.setString(1, "%" + keySkills + "%");
The JDBC code will replace ?
with a prepared statement value, coerced
to the expected SQL string type. And setString
takes care of escaping apostrophes and others.
Upvotes: 2
Reputation: 164064
You can use concat()
:
String query =
"SELECT F_Name, L_Name, Experience, Key_Skills " +
"FROM Candidate cd JOIN Candidate2 cd2 ON (cd.Mobile = cd2.C_Mobile) " +
"WHERE Key_Skills LIKE concat('%', ?, '%')";
When you execute the above code by passing a parameter say 'someskill'
the function concat()
will produce this string '%someskill%'
and the column Key_Skills
will be compared to this concatenated string.
Upvotes: 4