像关键字和反斜杠问题

时间:2012-08-01 15:12:30

标签: h2

如果我使用“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();
}
}

1 个答案:

答案 0 :(得分:2)

反斜杠是default escape character for LIKE conditions

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