From: eiichi_maekawa@... Date: 2010-01-06T09:59:12+09:00 Subject: [ruby-list:46734] Re: ruby-list:46730 Re: MySQLテーブル数の把握 前川です。 竹山さん、小川さん、伊達さん ありがとうございました。 冗長ですが、実施した結果を以下に記載しました。 実行したコーディング #!D:/Ruby/bin/ruby.exe -Ks require 'dbi' begin dbh = DBI.connect('DBI:Mysql:fbsys:a28341', 'dbuser01', 'dbkey') sth = dbh.prepare('show tables') puts dbh puts sth sth.execute puts 'table count='+sth.rows.to_s #←追加したステートメント sth.execute の 後でなければ、無意味ですね。 count = 0 sth.fetch { |row| p row count = count + 1 } sth.finish puts 'count='+count.to_s #DB例外発生時の処理 rescue DBI::DatabaseError => e p "An error occurred" p "Error code: #{e.err}" p "Error message: #{e.errstr}" #切断漏れしないようにensureでdisconnectします。 ensure dbh.disconnect if dbh end 実施結果::デバッグライト # # table count=9 #←たしかに、テーブル数が取れています。 ["aplist"] ["chistory"] ["efbinput"] ["fbginput"] ["fbinput"] ["fbninput"] ["kfiletable"] ["sffiletable"] ["sfiletable"] count=9 > DBI::StatementHandle#rows で結果の行数を得ることができます。 > http://ruby-dbi.rubyforge.org/rdoc/classes/DBI/StatementHandle.html#M000230 > sth = dbh.execute('show tables') > puts sth.rows #=> 9 全く、気づきませんでした。英文は、しんどいですが、読みます。 > あるいは、MySQL5であれば information_schema を使って取得することもできま す。 > sth = dbh.execute("select count(table_name) from > information_schema.tables where table_schema = 'fbsys'") > puts sth.fetch_all #=> 9 ふーむ、infomation_schemaにあるんですか。 MySQLのツール(MySQL Administrator,MySQLQueryBrowser)を利用して調べてみま す。 >RDoc によると,sth.rows で結果の行数が返るようです. >http://ruby-dbi.rubyforge.org/rdoc/index.html rows (DBI::StatementHandle) 今後、参考にします。RDocは、全く気づいてませんでした。 本当にありがとうございました。 データ件数(行数)や、列(columns)件数の取得などに応用させてもらいます。