• 締切済み

DBI

DBIを使ってテーブルを作成するステートメントの文字列を処理 したいのですがSQL文を実行してからの取り回しがわかりません どなたか教えてください。 $sth = $dbh->prepare(\" show create table sample000; \"); print \"$sth\\n\"; 出力結果DBI::st=HASH(0x111111111)

  • Perl
  • 回答数1
  • ありがとう数2

みんなの回答

  • zxcv0000
  • ベストアンサー率56% (111/196)
回答No.1

connect して dbh(データベース・ハンドル・オブジェクト)を得る所まではOKなんですね? なら、あと少しです。 1 正常か異常かが判れば良い SQL の実行の例 $dbh->do("CREATE TABLE 必要な指定...") or die($dbh->errstr()); 2 テーブルからデータを入力しながら配列に溜める例 my $sth = $dbh->prepare("SELECT * FROM mytbl") or die($dbh->errstr()); $sth->execute() or die $sth->errstr(); my @datas = (); while( my $ary_ref = $sth->fetchrow_arrayref() ) { push(@datas, [@$ary_ref]); # 返された $ary_ref 自身の記憶は危険 } if( $sth->err() ) { die $sth->errstr(); }

関連するQ&A

  • MySQLのトランザクションについて

    初めて質問します。 今、PerlのDBIを使ってMySQLのトランザクション処理にチャレンジしています。 ところが、rollback処理がうまくできません。 具体的には、 table2 がある状態で下のプログラムを動かすと、 エラーの表示が出るのに、 table1 は作成されました。 何らかのエラーがあれば、どちらも作成されないようにしたいです。 ======================================================= my %sql; $sql{db_name} = "database"; $sql{host} = "localhost"; $sql{user_name} = "user_name"; $sql{password} = "password"; use DBI; my $dbh = DBI->connect('DBI:mysql:'.$sql{db_name}.':'.$sql{host}, $sql{user_name}, $sql{password} ,{RaiseError => 1, PrintError => 0, AutoCommit => 0 }) || &Err(); my $sth; my $re; eval { my $sql_string1 = "create table table1(`id` int);"; my $sql_string2 = "create table table2(`id` int);"; $sth = $dbh->prepare($sql_string1); $re = $sth->execute; $sth = $dbh->prepare($sql_string2); $re = $sth->execute; }; if ($@) { $tag="Err:".$@."\n"; $sth = $dbh->rollback; }else{ $sth = $dbh->commit; } $sth->finish; $dbh->disconnect; ======================================================= 検索して、いろいろいじっても解決しませんでした。 どうかよろしくお願いします。

    • ベストアンサー
    • Perl
  • Perl・DBIでの汎用selectサブルーチンを作成するには?

    Perl・DBIで、select文発行のサブルーチンを作成していますが、未熟なため、完成できません。 呼び出し側では、下の記述のように、サブルーチンの引数として、SQL文を渡し(SELECT系)、戻り値として、SELECTされた結果を取得したい(配列もしくは、ハッシュで)と思っております。 もし、参考にできる、サイト・ サンプルサイト等のご紹介でも、結構ですので、ご教授くださればと思います。(処理の流れ等の箇条書きでもかまいません。) -------------------------------------------- # 呼び出し側(メインルーチン) $name;#テンプレート置換変数  $age; #テンプレート置換変数 my $sql =<<"EOQ"; # この抽出select文はその都度変わる。 select NAME,AGE from EMP EOQ my @row = &do_select($sql); $name = $row[0]; $age = $row[1]; もしくは、 $name = $hash_ref->{NAME}; $age = $hash_ref->{AGE}; のような記述で代入。 # テンプレートを読み込んで、置換処理で代入 ※幾分省略しています。 <table> for(){# SELECT分の結果の行数分繰り返し処理。 <tr>  <td>$name</td>  <td>$age</td> </tr> } </table> my $dbh = DBI->connect($dbhost, $dbuser, $dbpass) || die $dbh::errorstr; ##### select発行サブルーチン ####### sub do_select{ my $sth; my $rv; my @row; # 戻り値(フィールドが入る) my %dbhash; # 戻り値はこちらかな? my $sql = shift(@_); # select文 $sth = $dbh->prepare("$sql"); $rv = $sth->execute || die $sth->errstr; while($hash_ref = $sth->fetchrow_hashref){      # print "$hash_ref->{TITLE}<br>"; # ここに、何かの処理が入る } return @row; }

    • ベストアンサー
    • Perl
  • PerlでSQLiteを使おうとしてもうまく行きません

    下記のような感じでPerlプログラムからSQLiteのデータベースから読み出すプログラムを組んでみました。 もちろん、実際にデータベースのファイルを作ってあります。 下のように、かなりシンプルで簡単なプログラムですし、 間違ってもいないとは思うのですが・・・ use DBI; $db = DBI->connect("dbi:SQLite:dbname=accountdb","","",); $sth = $db->prepare("SELECT * FROM user"); $sth->execute;#結果を取得しresに代入 print "$sth\n"; $sth->finish; exit; 上を実行した結果は、下記の通りです。 DBI::st=HASH(0x32706c4) closing dbh with active statement handles during global destruction. 私が思うに、データが$sthに帰って来ると思うのですが、 実際にはDBI::st=HASH(*****)のようなものしかかえってきません アドバイスをどうか宜しく御願いします (別カテゴリで似たような質問をさせていただきましたが、これはまた別です・・・)

  • Ruby/DBI で.modeを使う方法

    sqlコマンドで.mode htmlを使ってからselectすると テーブルで返ってくるのでそのままrubyでも出力できるとコードが短くなって楽だと思ったんですが、うまくできません。 どうかやり方をお教えください。 rubyを始めたばかりでexecuteの実行結果がどのような構造になっているかもよくわかりません。 こちらの方もお教えいただけると幸いです。 下記のような使い方をしたいです。 <%# -*- coding:shift_jis -*- %> <% require 'rubygems' # RubyGems のインストール %> <% require 'dbi' #DBIの利用 %> <% dbh=DBI.connect('DBI:SQLite3:fruits.db') %> <% #HTML形式で受け取る %> <% #dbh.do(".mode html;") %> <%# execute select statement%> <% sth=dbh.execute("select * from fruits;") %> <html> <head> <meta http-equiv="Context-Type" content="text/html;charset Shift_JIS"/> <title>フルーツ管理</title> </head> <body> <% #テーブルで出力 %> <table> <%#=sth %> </table> </body> </html> <%# relese results %> <% sth.finish %> <%# disconnect database %> <% dbh.disconnect %>

  • PerlでDBIを使いますが、結果セットをフィールド名でアクセスするには?

    OSはWindowsでAccess2002のデータベースをODBC経由でDBIを用いて、Perlからアクセスします。 以下のように、結果セットをフィールド名でアクセスしたいです。 可能でしょうか? #!/perl/bin/perl #!/usr/bin/perl -w use DBI; # create the DSN connection $dsn = "dbi:odbc:test"; $dbh = DBI->connect($dsn) or die "接続エラー"; $query = "select * from goods;"; # execute the query $sth = $dbh->prepare($query); $sth->execute(); print "no name price\n"; print "--------------------------------------\n"; while(@item = $sth-> fetchrow) { #print "@item[0] @item[1] @item[2]"; #----- 通常はこうだが、 print "$item{'goods_name'} $item{'goods_price'} $item{'auto_no'}"; #----こんな感じで利用したい。 print ("\n"); } # disconnect $sth->finish(); $dbh->disconnect(); exit; __END__

    • ベストアンサー
    • CGI
  • perlでdb(mysql)に接続

    perlでdb(mysql)に接続し、取得したデータを 表示させるというようなことをしたいのですが、うまく いきません。 ファイル名test.cgi mysqlのバージョンは 5.0.45で 記述は以下です。 #!/usr/bin/perl use DBI; my $dbh = DBI->connect("DBI:mysql:database, "userid", "password"); my $sth = $dbh->prepare('SELECT * FROM tablename'); $sth->execute; print "Content-Type: text/plain\n\n"; print "\n"; while(my @row = $sth->fetchrow_array) { print "$row[0]:$row[1]\n"; } $sth->finish(); $dbh->disconnect(); exit; ブラウザで確認すると何も表示されず、ログとして 以下のエラーが確認できます。 DBD::mysql::st execute failed: Table 'database.tablename' doesn't exist at test.cgi line 8. DBD::mysql::st fetchrow_array failed: fetch() without execute() at test.cgi line 11. my $sth = $dbh->prepare('SELECT * FROM tablename'); で指定したテーブルは存在しておりますし、SQL文の記述も 問題ないと思われます。 また、ファイルのパーミッションは705(755でも同様の結果)です。 perl初心者のため、どこが問題なのか検討がつきません。 ご助言いただきたく存じます。 よろしくお願いいたします!

    • ベストアンサー
    • Perl
  • Mysqlの接続について

    現在、以下のようなperlのスクリプトを作っているのですが、mysqlへの接続,切断は以下の場合、どちらにした方がいいのでしょうか? (1)の場合 use DBI; $dsn="DBI:mysql:database=dbname:host=localhost"; $dbh=DBI->connect($dsn,'user','pass'); $sth = $dbh->prepare("SELECT no,title,name,date,host From `table1` where no='1'"); $sth->execute; $sth->fetchrow_array; $sth->finish; $sth2 = $dbh->prepare("SELECT no,title,name,date,host From `table2` where no='1'"); $sth2->execute; $sth2->fetchrow_array; $sth2->finish; $dbh->disconnect; (2)の場合 use DBI; $dsn="DBI:mysql:database=dbname:host=localhost"; $dbh=DBI->connect($dsn,'user','pass'); $sth = $dbh->prepare("SELECT no,title,name,date,host From `table1` where no='1'"); $sth->execute; $sth->fetchrow_array; $sth->finish; $dbh->disconnect; $dsn="DBI:mysql:database=dbname:host=localhost"; $dbh=DBI->connect($dsn,'user','pass'); $sth2 = $dbh->prepare("SELECT no,title,name,date,host From `table2` where no='1'"); $sth2->execute; $sth2->fetchrow_array; $sth2->finish; $dbh->disconnect; (1)の場合と(2)の場合の違いは、(1)の場合、最初にデータベースに接続して、一番最後に切断する事で、(2)の場合、毎回データベースへの接続と切断を行う事が違います。 (2)の場合、毎回接続と切断を行うので、2回ほどではあまり変わらないかもしれないのですが、もし10回とか接続と切断を行うとかなり負荷が高くなるような気がするのですが、他のHPなどを拝見すると接続をしたら切断を行うように癖をつけるようにした方がいいと書かれていたりします。 どちらの方が正しいやり方というか、負荷がすくなく使えるのでしょうか?

    • ベストアンサー
    • Perl
  • DBIモジュールと Perl5.8

    Perl5.8のエンコードが理解できずに困っております。 MySQLでは、utf8の文字コードのデータがあります。 以下のスクリプトを実行させると、 Wide character in print at C:/usr/local/site/lib/DBI.pm line 1008. となります。 対処方法はあるのでしょうか? use utf8; use strict; use DBI; my $dbh = DBI->connect("dbi:mysql:dbname=test", "root", "", { AutoCommit=>1, PrintError=>1, RaiseError=>1} ); my $fname = "test.txt"; my $sth = $dbh->prepare("select id, namae from test order by id asc;"); $sth->execute(); # 出力ファイルを開く。 open FILE, ">" , $fname or die "Can't open $fname: $!"; # 整形された結果をファイルにダンプする。 my $rows = $sth->dump_results(80, "\n", ",", \*FILE); # 出力ファイルを閉じる。 close FILE or die "Error closing result file: $!\n"; $dbh->disconnect();

    • ベストアンサー
    • Perl
  • fetchrow_arrayとfetchrow_hashrefの使い方

    Jやまとです。 PerlからSELECT文を実行して結果の行の値を取得する単純なスクリプトを作成しています。 (1)fetchrow_array使用 (2)fetchrow_hashref使用 以上2通りの方法で試したのですが、(2)がInternal Server Errorになります。 原因が全く分かりません。 分かる方いらしゃいましたら、ご教授願います。 OS:TurboLinux6.2 DB:Oracle8i Apache,PerlはTurboLinux6.2に入っているものをそのまま使用 以下、ソースを記載します。 --------------- (1)fetchrow_arrayを使用して行の値を取得(こっちは動く) $dbh = DBI->connect($ds, $user, $pass) || &dbErr("Database can't connect." . $DBI::errstr); $sql = "SELECT SYSDATE FROM DUAL \n"; $sth = $dbh->prepare( $sql ); $sth->execute or die "Cannot execute. " . $sth->errstr(); $cnt1 =1; while (@row = $sth->fetchrow_array()) { @{$get_date[$cnt1]} = @row; $cnt1++; } --------------- (2)fetchrow_hashrefを使用して行の値を取得(こっちが動かない) $dbh = DBI->connect($ds, $user, $pass) || &dbErr("Database can't connect." . $DBI::errstr); $query = qq{ SELECT SYSDATE FROM DUAL }; $sth = dbh->prepare($query); $sth->execute(); # 実行 if($sth->rows() != 1){ # 該当する行数 # エラー処理 } $rhash = $sth->fetchrow_hashref(); %hash = {%{$rhash}}; $sth->finish(); $get_date = $hash{SYSDATE}; --------------- (2)実行時のerror_log Can't locate object method "prepare" via package "dbh" at /u01/ora1/www/htdocs/hoge.cgi line 30. Premature end of script headers: /u01/ora1/www/htdocs/hoge.cgi --------------- (本文長くてすみません)

    • ベストアンサー
    • Perl
  • perl >> DBI >> DBD >> oracle8でエラー

    perlからDBI経由でoracleに接続したいのですが、 なぜか DBI->connectのところで失敗して下記のようなエラーが出ます。 `CONNECT ERROR ORA-1034: ORACLE not available oas userでtelnetで入り、直接perl scriptを起動すると問題なく動作するの ですが、なぜかOAS経由でブラウザーからCGIとしてcallすると 失敗するのです。 もう2日も悩んでます。 どなたか原因がわかりましたらご教授ください。 ---- 環境 --- perl 5.005_03 OAS 4.0.8.1 DBI 1.30 DBD-Oracle 1.12 OS solaris2.6 接続先DBは別のsolarisマシンに入ってる。 ----------------ソース----------------------------- #!/usr/local/bin/perl use DBI; $dsn = 'DBI:Oracle:orcl'; $user = 'testuser'; $password = 'testuserpass'; $dbh = DBI->connect($dsn, $user, $password) or die "接続できません"; my $sth = $dbh->prepare("select * from munec"); $sth->execute; while(@row = $sth->fetchrow_array) { print "@row\n"; } ---------------

専門家に質問してみよう