ikepyonのだめ人間日記

セキュリティに関することを書いていく予定。

MySQLのPreparedStatement

というわけで、実証コード例を作った。SQLインジェクションが発生していれば、「result:0」にはならない。
徳丸さんのサンプルコードをパクって見たw(Thx:徳丸さん)

import java.sql.*;

public class TestUnicode {

  /**
   * @param args
   */
  public static void main(String[] args) throws Exception {
        try {
          String charEncoding = "sjis";
          Class.forName("com.mysql.jdbc.Driver");
          Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost/test?user=root&useUnicode=true&characterEncoding=" + charEncoding);
          Statement stmt = con.createStatement();

          String param = "\u00a5'or 1=1#";

          stmt.execute("create table if not exists test (name text, id INT UNSIGNED NOT NULL AUTO_INCREMENT, primary key(id));");
          stmt.execute("insert into test (name) values ('test');");
          stmt.execute("insert into test (name) values ('test2');");
          String sql = "SELECT count(*) FROM test WHERE name = ? ;";
          PreparedStatement preparedStmt = con.prepareStatement(sql);
          
          preparedStmt.setString(1, param);
          ResultSet rs = preparedStmt.executeQuery();
          while(rs.next()){
            int id = rs.getInt(1);
            System.out.println("result:" + id);
          }
          stmt.close();
          preparedStmt.close();
          con.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
  }

}