我正在尝试从我的java代码中查询MS Access数据库,并且我没有运气,我读过的%通配符应该在其他帖子中工作。如果从代码中排除通配符并为searchText变量提供与记录描述完全匹配的值,LIKE运算符将起作用。下面是我尝试过的字符串查询,它们返回null或异常:
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);
非常感谢任何帮助。
答案 0 :(得分:1)
你无论如何都会遇到语法错误:
String query = String.format([..snip...] + " LIKE '%" searchText
^---missing +
答案 1 :(得分:1)
百分号(%
)绝对是在这种情况下使用的正确通配符。对于测试数据
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
代码
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)));
}
生成以下控制台输出
1: I like apple pie.
3: Apple makes iThings.
5: Name of a tropical fruit: pineapple