電子書籍の厳選無料作品が豊富!

ファイルデータ内容を SQL条件へ代入する方法を教えてください。
例)ファイル(1)
あいう
かき
さしす
あかさたな

これを SQLのWhere区に 条件設定したい。
SELECT XXX FROM VVV where(ZZZ LIKE 'あいう' OR ZZZZ LIKE 'かき' OR …);
という風にファイルの行があるだけ すべてLIKE条件にいれられて、一度に計算できるようにしたい。
Perl(またはShell)プログラムで ファイル読込、SQLの実行をして、結果を取得する方法をおしえてください。
プログラムは詳しくないので、詳細に書き方を教えていただけると幸いです。
よろしくお願いいたします。

A 回答 (2件)

これは、俺が年に数回やっている仕事と同じだな。


100万円払えば、土日に教えてあげるよ。
    • good
    • 0

use DBI;



# DB Name
my $db_name = 'sqlite_test.db';
unlink $db_name;

my @user_infos = (
  { id => 1, name => 'Alice' },
  { id => 2, name => 'Bob' },
  { id => 3, name => 'Carol' },
  { id => 4, name => 'David' },
);

print '--- Connect DB', "\n";
my $dbh = DBI->connect(
  'dbi:SQLite:dbname=' . $db_name,
  '', '',
  {  AutoCommit => 0,
    RaiseError => 1
  }
) || die "$db_name : $!";

my $sql;
my $table = 'user_info';

print '--- Create Table', "\n";
$sql = 'CREATE TABLE ' . $table . '(id integer primary key, name)';
$dbh->do($sql) or die $dbh->errstr;
$dbh->commit  or die $dbh->errstr;

my $sth;
print '--- Insert Record', "\n";
$sth = $dbh->prepare( 'INSERT INTO ' . $table . '(id, name) VALUES (?, ?)' )
  || die $dbh->errstr;
for my $info_ref (@user_infos) {
  $sth->bind_param( 1, $info_ref->{id} )  or die $sth->errstr;
  $sth->bind_param( 2, $info_ref->{name} ) or die $sth->errstr;
  $sth->execute or die $dbh->errstr;
  $dbh->commit or die $dbh->errstr;
}

print '--- Select Record', "\n";
$sql = "SELECT * FROM $table WHERE name LIKE ? OR name LIKE ?";
$sth = $dbh->prepare($sql) || die $sth->errstr;
$sth->bind_param( 1, '%Bob%' )  or die $sth->errstr;
$sth->bind_param( 2, '%Carol%' ) or die $sth->errstr;

print '--- use fetch (fetchrow_arrayref)', "\n";
$sth->execute or die $sth->errstr;
while ( my $ref = $sth->fetch() ) {
  print "@$ref\n";
}
if ( $sth->err ) {
  die $sth->strerr;
}
$dbh->commit or die $dbh->errstr;

print '--- end of procedure', "\n";
$sth->finish or die $sth->errstr;
undef $sth; # fail safe
$dbh->disconnect or die $dbh->errstr;
unlink $db_name or die "$db_name : $!";

# result
# $ perl -w foo.pl
# --- Connect DB
# --- Create Table
# --- Insert Record
# --- Select Record
# --- use fetch (fetchrow_arrayref)
# 2 Bob
# 3 Carol
# --- end of procedure
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!