I cannot select a backslash from a table if I use the “like” keyword.
it’s working fine with the derby database, so I want to ask is the sql incorrect? or the backslash has special meaning in h2?
Thank you:)
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();
}
}
The backslash is the default escape character for LIKE conditions.
I guess you need to use two backslashes, that is, within Java, you need to write
"\\\\". Or, as an alternative, useLIKE '\' ESCAPE ''(to use no escape character).