====== SQLの実行 ====== ===== 概要 ===== select文は、返り値が必要な関係上、select()メソッドを使います。\\ insert,update,delete文は、任意のSQLを実行するexecute()メソッドを使う方法と、各ヘルパーメソッドを使う方法があります。\\ その他のSQL文は、execute()メソッドを使います。 ===== selectメソッド ===== SQLが確定している場合の例です。 res = db.select( "select * from t1 where valid = 1;" ) select()の返り値は、デフォルトでHashのArrayです。 [ {:id=>1, :name=>"ange",...}, {:id=>2, :name=>"bob",...} ] where条件がある場合、プレースホルダを使います。\\ ただし、プレースホルダの書式はRDBMSによって統一されておらず、注意が必要です。\\ パラメータは、第2引数に配列で指定します。 res = db.select( "select * from t1 where id=?;", [2] ) # SQLite, MySQL res = db.select( "select * from t1 where id=$1;", [2] ) # PostgreSQL where条件パラメータは、Hashで指定する方法もあります。\\ 上記方法に比べ、AND条件しか指定できない等自由度が低下しますが、DB間の差異はAloneが吸収します。\\ SQL文中に、マジックワード _WHERE_ を挿入して、そこへHashで指定された条件をANDで接続して挿入します。 res = db.select( "select * from t1 _WHERE_;", { :id=>2, :age=>nil, "name like"=>"a%" } ) # => select * from t1 where id=2 and age is null and name like 'a%'; ===== 値の戻し方 ===== select()の返り値はデフォルトでHashのArrayで、全結果セットを一括で取得します。\\ この動作は、変更することもできます。 1.結果を、Arrayで受け取る @db = AlRdbw.connect( DSN ) @db.select_data_type = :ARRAY res = @db.select( sql ) #=> [[1, "ange"], [2, "bob"]] fields = @db.fields() #=> [:id, :name] 2. 結果を、1行ずつ受け取る @db = AlRdbw.connect( DSN ) @db.select_fetch_mode = :ROW res = @db.select( sql ) #=> {:id=>1, :name=>"ange"} while res p res res = @db.select_next() #=> {:id=>2, :name=>"bob"} end ===== ヘルパーメソッド ===== insertの例 values = { :id=>3, :name=>"smith" } res = db.insert( "table_name", values ) updateの例 values = { :name=>"smith", :age=>10 } where_cond = { :id=>3 } res = db.update( "table_name", values, where_cond ) deleteの例 where_cond = { :id=>3 } res = db.delete( "table_name", where_cond ) ===== 任意SQLの実行 ===== 任意のSQLを実行します。 res = db.execute( "lock table t1;" ) select()と同様の方法で、パラメータクエリも実行できます。 res = db.execute( "delete from t1 where = ?;", [3] )