Flex、Ruby、MySQLの連携
今回やってみたのは以下の二つ。
FlexからRubyへ送信したデータのデータベースへの格納。
Ruby側でデータベース内のデータを取り出しXMLを生成。それをFlexへ送信して表示。
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundGradientAlphas="[1.0, 1.0]" backgroundGradientColors="[#FC0000, #000000]"> <mx:Script> <![CDATA[ import mx.controls.Alert; ]]> </mx:Script> <mx:HTTPService id="insert_sv" url="http://www11.atpages.jp/~matsu4512/flex/MySQL_Ruby/insert.cgi" method="GET" result="Alert.show('INSERT 成功'); input_txt.text='';" fault="Alert.show('INSERT 失敗')"/> <mx:HTTPService id="select_sv" url="http://www11.atpages.jp/~matsu4512/flex/MySQL_Ruby/select.cgi" method="GET" resultFormat="e4x"/> <mx:Panel x="10" y="10" width="365" height="79" layout="absolute" title="INSERT"> <mx:Button x="287" y="10" label="送信" click="insert_sv.send({name:input_txt.text})"/> <mx:TextInput x="10" y="10" id="input_txt" width="269"/> </mx:Panel> <mx:Panel x="13" y="97" width="362" height="375" layout="absolute" title="SELECT"> <mx:DataGrid x="10" y="10" width="322" height="284" dataProvider="{select_sv.lastResult..student}"> <mx:columns> <mx:DataGridColumn headerText="id" dataField="id"/> <mx:DataGridColumn headerText="Name" dataField="name"/> </mx:columns> </mx:DataGrid> <mx:Button x="276" y="302" label="GET" click="select_sv.send()"/> </mx:Panel> </mx:Application>
INSERT
#!/usr/local/bin/ruby require "mysql" require "cgi" #ヘッダー print "Content-Type: text/html\n\n" #GETで受け取ったパラメータの取得 cgi = CGI.new() name = cgi["name"] #データベースへの接続 db = Mysql.new('ホスト名', 'ユーザー名', 'パスワード', 'データベース名') #SQL文の実行 db.query("INSERT INTO students(name) VALUES(\'#{name}\')")
SELECT
#!/usr/local/bin/ruby require "mysql" #ヘッダー print "Content-Type: text/xml\n\n" #データベースへの接続 db = Mysql.new('ホスト名', 'ユーザー名', 'パスワード', 'データベース名') res = db.query('SELECT * FROM students') #XMLの生成 puts '<students>' #連想配列でデータを処理 res.each_hash do |obj| puts '<student>' puts "<id>#{obj['id']}</id>" puts "<name>#{obj['name']}</name>" puts '</student>' end puts '</students>'