PreparedStatementでワイルドカードを含む文字列を検索する方法
- 2011.05.31
- IT関連

こんばんは。kinokoです。
今、Java(ServletやJSPなど)について勉強中なのですが、PreparedStatementで ‘?’ を使ってパラメータクエリを発行するときに、ワイルドカードを含む文字列を直接エスケープして検索することが出来ません。
PreparedStatement pstmt = conn.prepareStatement(“select * from hogehoge where hoge like ? {escape ‘\\’}”);
これは出来ない。
そこで、自作関数を使って一文字ずつ置換する方法で解決したので、覚え書き。
// SQL文出力用に ‘%’ と ‘_’ の置換を行う
private String EscapeSQL(String input) {
input = SQLescape(input, “%”, “\\%“);
input = SQLescape(input, “_”, “\\_”);
return input;
}
public String SQLescape(String input, String pattern, String replacement) {
//置換対象文字のindexを取得し、なければ何もせずに戻す
int index = input.indexOf(pattern);
if(index == -1) {
return input;
}
StringBuffer buffer = new StringBuffer();
buffer.append(input.substring(0, index) + replacement);
if(index + pattern.length() < input.length()) {
String rest = input.substring(index + pattern.length(), input.length());
buffer.append(SQLescape(rest, pattern, replacement));
}
return buffer.toString();
}
やっぱり、SQLって難しい。
-
前の記事
S2JDBCでのページング処理 2011.05.31
-
次の記事
干し野菜がブーム? 2011.05.31