0

如果我使用“like”关键字,我无法从表中选择反斜杠。它与derby数据库一起工作正常,所以我想问一下sql是否不正确?还是反斜杠在 h2 中有特殊含义?谢谢:)

public class HelloWorld {
public static void main(String... args) throws Exception {
    // delete the database named 'test' in the user home directory
    DeleteDbFiles.execute("~", "test", true);
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:~/test");
    Statement stat = conn.createStatement();
    stat.execute("create table test(" +
            "id int primary key, " +
            "name varchar(255))");
    try {
        int id = 1;
        String name = "\\";
        stat.execute("insert into test values("+id+",'"+name+"')");
        ResultSet rs = stat.executeQuery("select * from test");
        while(rs.next()) {
            System.out.println(rs.getString(1)+" "+rs.getString(2));
        }
        ResultSet rs2 = stat.executeQuery(
              "select * from test where name like '"+name+"%'");
        // ResultSet rs2 = stat.executeQuery(
              "select * from test where name = '"+name+"'");
        while(rs2.next()) {
            System.out.println(rs2.getString(1)+" "+rs2.getString(2));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    stat.close();
    conn.close();
}
}
4

1 回答 1

3

反斜杠是LIKE 条件的默认转义字符

我猜你需要使用两个反斜杠,也就是说,在 Java 中,你需要写"\\\\". 或者,作为替代方案,使用LIKE '\' ESCAPE ''(不使用转义字符)。

于 2012-08-01T15:44:12.917 回答