Pergunta

I am trying to query a MS Access database from my java code and I am having no luck with the % wildcard that I read should work in other posts. The LIKE operator works if I exclude the wild cards from my code and provide the searchText variable with a value that matches exactly to a records Description. Below is the String queries I have tried that have either returned null or an exception:

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '%" searchText +  "%' ORDER BY [WorkOrderNo] DESC", tableName);

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '*" searchText +  "*' ORDER BY [WorkOrderNo] DESC", tableName);

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \"%" searchText +  "%\" ORDER BY [WorkOrderNo] DESC", tableName);

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

String tableName = "SSPWO"; String desc = "[Description]";

  String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \'%" searchText +  "%\' ORDER BY [WorkOrderNo] DESC", tableName);

Any help is greatly appreciated.

Foi útil?

Solução

The percent sign (%) is definitely the right wildcard character to use in this case. For test data

ID  Description                        
--  -----------------------------------
 1  I like apple pie.                  
 2  This is a test.                    
 3  Apple makes iThings.               
 4  This is another test.              
 5  Name of a tropical fruit: pineapple

the code

String tableName = "SSPWO"; 
String desc = "[Description]";
String searchText = "apple";
PreparedStatement ps = con.prepareStatement(
        String.format("SELECT * FROM %s WHERE %s LIKE ?", tableName, desc)
        );
ps.setString(1, "%" + searchText + "%");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    System.out.println(String.format("%d: %s", rs.getInt(1),rs.getString(2)));
}

produces the following console output

1: I like apple pie.
3: Apple makes iThings.
5: Name of a tropical fruit: pineapple

Outras dicas

You've got a whack of syntax errors anyways:

String query = String.format([..snip...] + " LIKE '%" searchText 
                                                     ^---missing +
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top