忍者ブログ

Wordpressメモとかアフィめもとか

Wordpress,PHP,アフィリエイトとかの個人メモを記録していくよ

[PR]

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

perl DBI シングルクォーテーションのエスケープ

perlに限らず当たり前の事だけど、INSERTする前にシングルクォーテーションはエスケープしましょう。
こんなエラー出ちゃう。

DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ...

$sql =~ s/\'/\'\'/g;

$dbh->quote()を使ったり、そもそもバインドしてから実行すれば、特殊文字もただの文字列として扱われるみたい。

$sth = $dbh->prepare(
    "UPDATE hoehoe SET PASS=? WHERE USER=? and PASS=?") or die;
$sth->execute($newpwd, $user, $oldpwd);






拍手[0回]

PR

perlで@INCにパスを追加

実行時にオプションを渡す方法

perl -I /INCPATH exsample.pl


BEGINで宣言

BEGIN{
push{@INC, 'INCPATH');
}


use libで宣言

#!/usr/bin/perl

use strict;
use warnings;
use lib 'INCPATH';


コレで@INCのパスにINCPATHが追加されるので、自作モジュールをおいておけば呼び出し元がどこにあっても使える。

拍手[0回]

perl出よく出る Use of uninitialized value in concatenation (.) or string at

Use of uninitialized value in concatenation (.) or string atというエラー

初期化しないで変数を使うから。

#!/usr/bin/perl
 
use warnings;
use strict;
 
my $hello;
print "$hello\n";

↓のようにするとか
my $hello = '';
print "$hello\n";

拍手[0回]

perlのDBI関連でよく出るエラーと対処?

Can't call method ``prepare'' without a package or object reference
prepareする前のconnectが失敗してるかも。DBIメソッドの戻りステータスをチェックする。$DBI:errstrとか。

Can't call method ``execute'' without a package or object reference
prepareメソッドが失敗したのでexecuteに使った$sthハンドルが未定義になってる。上と同じでDBIメソッドの戻ステータスをチェックする。

古いけどここらへんを参考に。
DBIモジュール Ver. 1.19

拍手[0回]

perl DBI モジュールのメソッドをuseして使う

色々なスクリプトからDB接続をするので、DBIモジュールのメソッドを共通関数用のpackageにいれたいなーと、、、

ちょっとはまったのでメモ。

perlでDBIモジュールをつかってMysqlへ接続するのは、そこらじゅうに記述があるので割愛。

やりたかったのは、DBIメソッドのconnectとかdisconectとかをpackage化して使いたかった。

[main.pl]

#!/sur/bin/perl

use strict;
use warnings;
use DBI;

use Func;

my $ret;
my $sql;

eval{
  $ret = conDB(dsn, user, pass);
  ・・・中略
  $sql = "select * from xx where xx";
  $ret = exec_sql($sql);
  ・・・中略
  $ret = disconDB;
};
if( $@ ){
  #エラー処理
}
exit;


[Func.pm]

package Func;

use strict;
use warnings;
use Exporter;
our @ISA = qw( Exporter );
our @EXPORT = qw( conDB exec_sql disconDB );
our $dbh;

sub conDB{
  my $dsn = $_[0];
  my $user = $_[1];
  my $pass = $_[2];

  $dbh = DBI->connect($dsn, $user, $pass
                       {RaiseError => 1 ,PrintError => 1 , AutoCommit => 0}) or die "DB connect Error :$!";
}

sub exec_sql{
  my $sql = $_[0];
  my $ret;
  my $sth;
  $ret = $sth->fetchall_arrayref;
  return $ret;
}

sub disconDB{
  $dbh->disconnect;
}

戻り値チェックとか細かいのははしょっているけど、データベースハンドルとして使っている$dbhをpackage側でour宣言しないと、main.plでconnectした後のexec_sqlにデータベースハンドルが引き継がれないのでエラーになっちゃうと言うお話。
main.plでour宣言してた、、、。


拍手[0回]

ブログ内検索

最新コメント

広告

プロフィール

なんとなくはじめてみたよ

忍者ツールズプロフィールは終了しました

カウンター