内容へ移動
alone-doc
ユーザ用ツール
ログイン
サイト用ツール
検索
ツール
文書の表示
バックリンク
メディアマネージャー
サイトマップ
ログイン
>
メディアマネージャー
サイトマップ
現在位置:
start
»
alrdbw
»
sqlの実行
トレース:
alrdbw:sqlの実行
この文書は読取専用です。文書のソースを閲覧することは可能ですが、変更はできません。もし変更したい場合は管理者に連絡してください。
====== SQLの実行 ====== ===== 概要 ===== select文は、返り値が必要な関係上、select()メソッドを使います。\\ insert,update,delete文は、任意のSQLを実行するexecute()メソッドを使う方法と、各ヘルパーメソッドを使う方法があります。\\ その他のSQL文は、execute()メソッドを使います。 ===== selectメソッド ===== SQLが確定している場合の例です。 <code ruby> res = db.select( "select * from t1 where valid = 1;" ) </code> select()の返り値は、デフォルトでHashのArrayです。 <code ruby> [ {:id=>1, :name=>"ange",...}, {:id=>2, :name=>"bob",...} ] </code> where条件がある場合、プレースホルダを使います。\\ ただし、プレースホルダの書式はRDBMSによって統一されておらず、注意が必要です。\\ パラメータは、第2引数に配列で指定します。 <code ruby> res = db.select( "select * from t1 where id=?;", [2] ) # SQLite, MySQL res = db.select( "select * from t1 where id=$1;", [2] ) # PostgreSQL </code> where条件パラメータは、Hashで指定する方法もあります。\\ 上記方法に比べ、AND条件しか指定できない等自由度が低下しますが、DB間の差異はAloneが吸収します。\\ SQL文中に、マジックワード _WHERE_ を挿入して、そこへHashで指定された条件をANDで接続して挿入します。 <code ruby> 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%'; </code> ===== 値の戻し方 ===== select()の返り値はデフォルトでHashのArrayで、全結果セットを一括で取得します。\\ この動作は、変更することもできます。 1.結果を、Array<Array>で受け取る <code ruby> @db = AlRdbw.connect( DSN ) @db.select_data_type = :ARRAY res = @db.select( sql ) #=> [[1, "ange"], [2, "bob"]] fields = @db.fields() #=> [:id, :name] </code> 2. 結果を、1行ずつ受け取る <code ruby> @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 </code> ===== ヘルパーメソッド ===== insertの例 <code ruby> values = { :id=>3, :name=>"smith" } res = db.insert( "table_name", values ) </code> updateの例 <code ruby> values = { :name=>"smith", :age=>10 } where_cond = { :id=>3 } res = db.update( "table_name", values, where_cond ) </code> deleteの例 <code ruby> where_cond = { :id=>3 } res = db.delete( "table_name", where_cond ) </code> ===== 任意SQLの実行 ===== 任意のSQLを実行します。 <code ruby> res = db.execute( "lock table t1;" ) </code> select()と同様の方法で、パラメータクエリも実行できます。 <code ruby> res = db.execute( "delete from t1 where = ?;", [3] ) </code>
alrdbw/sqlの実行.txt
· 最終更新:
2023/08/17 12:13
by
hirohito
ページ用ツール
文書の表示
バックリンク
文書の先頭へ