SQLiteを操作するAirアプリケーションを作成する 3-1(Insert編)

前回はテーブル作成のロジックを作成した所まで。

次にinsertするロジックと画面を作成して実際にテーブルにinsertしてみる

  1. insertのロジックを下記の様に書いてみる
    private function insert():void {
       stmt = new SQLStatement();
       stmt.sqlConnection = sqlConn;
       stmt.text = "INSERT INTO idol (name,height,weight,birthday,bust,waist,hip,age) "+
       "VALUES ("+ 
          "'"+ nameFieldId.text +"',"+
          heightFieldId.text +","+
          weightFieldId.text +","+
          "'"+ birthdayFieldId.text +"',"+
          bustFieldId.text +","+
          waistFieldId.text +","+
          hipFieldId.text +","+
          ageFieldId.text+
       ")";
    				
       try{
          stmt.execute();
          successResult();
       }catch(error:Error){
          errorResult(error);
       }
    }
    
  2. 続いて画面の方は適当にこんな感じ
    </fx:Script>
    <mx:VBox verticalGap="0">
        <mx:Canvas width="100%">
            <mx:Label text="名前" x="{nameFieldId.x}" />
            <mx:Label text="身長" x="{heightFieldId.x}" />
            <mx:Label text="体重" x="{weightFieldId.x}" />
        </mx:Canvas>
        <mx:HBox width="100%">
            <mx:TextInput id="nameFieldId"/>
            <mx:TextInput id="heightFieldId" restrict="[0-9]" maxChars="3"/>
            <mx:TextInput id="weightFieldId"/>
        </mx:HBox>
        <mx:Canvas width="100%">
            <mx:Label text="バスト" x="{bustFieldId.x}" />
            <mx:Label text="ウエスト" x="{waistFieldId.x}" />
            <mx:Label text="ヒップ" x="{hipFieldId.x}" />
        </mx:Canvas>
        <mx:HBox width="100%">
            <mx:TextInput id="bustFieldId"/>
            <mx:TextInput id="waistFieldId"/>
            <mx:TextInput id="hipFieldId"/>
        </mx:HBox>
        <mx:Canvas width="100%">
            <mx:Label text="誕生日" x="{birthdayFieldId.x}" />
            <mx:Label text="年齢" x="{ageFieldId.x}" />
        </mx:Canvas>
        <mx:HBox width="100%">
            <mx:TextInput id="birthdayFieldId"/>
            <mx:TextInput id="ageFieldId" restrict="[0-9]" maxChars="3"/>
        </mx:HBox>
    </mx:VBox>
    <mx:HBox>
    	<mx:Button id="insertBtn" label="登録" click="insert()" />
    </mx:HBox>
    
  3. これでコンパイルしてみて、エラーが出ないことを確認する
  4. ただし上記コードだとロジック部分に大きな問題がある
    • 値のチェックを行なっていない為、全項目を入力しないと正常にInsert出来ない。具体的には
      INSERT INTO idol (name,height,weight,birthday,bust,waist,hip,age) VALUES ('',,,'',,,,)
      というSQLが発行される可能性があり、エラーになってしまう。本来は
      INSERT INTO idol (name,height,weight,birthday,bust,waist,hip,age) VALUES ('',NULL,NULL,'',NULL,NULL,NULL,NULL)
      の様なSQLが発行されるのが望ましい。ハズ。 なので値のチェックを行い、正常なSQL文を作成する必要がある
    • InsertのSQL文に画面上からのデータをただ連結し実行するのはセキュリティ上望ましくなく、このままではSQLインジェクションが起こる可能性がある。SQLインジェクションの対応の一つとしてプリペアドステートメントを利用する方法があるので、次回辺りにその変更を行う。今回はこれでも書けますよって話。実際書けることは書けるが、書かないほうがいい