I'm trying to figure this but without success. I'm trying to find every row in a specific table that contains a value.
For example, let's consider this Employee table:
| Id | First_name | Last_name | Date_of_birth | Car_number |
|------------------|------------|------------|---------------|------------|
| 10001 | John | Washington | 28-Aug-43 | 5 |
| 10083 | Arvid | Sharma | 24-Nov-54 | null |
| 10034 | David | Johnson | 12-May-76 | |
I'm building this query on the Java side (this is what I print in the log):
Select * From Employee WHERE Id LIKE ? OR First_name LIKE ? OR Last_name LIKE ? OR Date_of_birth LIKE ? OR Car_number LIKE ?
then I use a prepared statement so that, if I search for the string 'oh' it becomes:
Select * From Employee WHERE Id LIKE '%oh%' OR First_name LIKE '%oh%' OR Last_name LIKE '%oh%' OR Date_of_birth LIKE '%oh%' OR Car_number LIKE '%oh%'
Here's the corresponding code:
String wantedQuery = "Select * From " + tableName + " WHERE";
PreparedStatement preparedStatement;
try(ResultSet rsColumns = columnsForTable(tableName)) {
String keyword = keywordField.getText();
int limit = 0;
while (rsColumns.next()) {
wantedQuery += " " + rsColumns.getString(1) + " LIKE ? OR";
limit++;
}
wantedQuery = wantedQuery.substring(0, wantedQuery.length()-3);
preparedStatement = con.prepareStatement(wantedQuery);
System.out.println(wantedQuery);
System.out.println("\'%"+keyword+"%\'");
for(int i = 1; i <= limit; i++) {;
preparedStatement.setString(i, "\'%"+keyword+"%\'");
}
}
try(ResultSet rs = preparedStatement.executeQuery()) {
//now get the results from here
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
System.out.println("Fetching row");
...
}
Now the problem is that when I try to get the results, it gives me 0 rows (I never see "Fetching row" printed) but the query works in SQL Developer. So I guess the error is on the Java side but I have any clue what it can be. Any ideas?
preparedStatement.setString(i, "\'%"+keyword+"%\'");