SQL を生成する文字列埋め込みに関する考察

 select * from Product where name = 'hoge';

hogeの部分に埋め込みをしたい.でもSQLインジェクションはさせたくない,という
場合になるべく簡単に書きたい.

  • 方法1:
 %word="It's ok";
 SQL s="select * from Product where name = #{word} ";

とかくと

 select * from Product where name = 'It\'s ok';

というように自動的に文字列リテラルになる.

  • 方法2:
 %word="It's ok";
 SQL s="select * from Product where name = '#{word}'";

と書くとコンパイルエラーになり

 %word=escape("It's ok");
 SQL s="select * from Product where name = '#{word}'";

と書くことを強制する.

ちなみに,escapeの定義はこう:

String matches /([^'\\]|\\.)+/ escape (s) {
  s =~ s/\\/\\\\/; 
  s =~ s/'/\\'/; 
  return s;
}

String matches regex は 「regexにマッチする文字列の型」のこと.