0

我需要使用 Perl 的DBI模块在数据库中插入值。我已经解析了一个文件来获取这些值,因此这些值存在于一个数组中,比如@array1, @array2, @array3。我知道如何一次插入一个值,但不知道如何从数组中插入。

我知道一次插入一个值:

$dbh = DBI->connect("dbi:Sybase:server=$Srv;database=$Db", "$user", "$passwd") or die "could not connect to database";
$query= "INSERT INTO table1 (id, name, address) VALUES (DEFAULT, tom, Park_Road)"; 
$sth = $dbh->prepare($query) or die "could not prepare statement\n";
$sth-> execute or die "could not execute statement\n $command\n";

我不确定我是否有包含 ID 的数组 1、包含名称的数组 2 和包含地址的数组 3,我将如何插入值。

4

4 回答 4

5

由于您有并行数组,因此您可以利用execute_array

my $sth = $dbh->prepare('INSERT INTO table1 (id, name, address) VALUES (?, ?, ?)');
my $num_tuples_executed = $sth->execute_array(
    { ArrayTupleStatus => \my @tuple_status },
    \@ids,
    \@names,
    \@addresses,
);

请注意,这是文档中截断(并稍作修改)的示例。如果您决定使用此功能,您肯定想查看其余部分。

于 2009-11-18T21:46:02.220 回答
2

使用占位符

更新:我刚刚意识到你有并行数组。这确实不是处理一起出现的数据项的好方法。有了这个警告,您可以使用List::MoreUtils::each_array

#!/usr/bin/perl

use strict; use warnings;

use DBI;
use List::MoreUtils qw( each_array );

my $dbh = DBI->connect(
    "dbi:Sybase:server=$Srv;database=$Db", 
    $user, $passwd, 
) or die sprintf 'Could not connect to database: %s', DBI->errstr;

my $sth = $dbh->prepare(
    'INSERT INTO table1 (id, name, address) VALUES (?, ?, ?)'
) or die sprintf 'Could not prepare statement: %s', $dbh->errstr;

my @ids = qw( a b c);
my @names = qw( d e f );
my @addresses = qw( g h i);

my $it = each_array(@ids, @names, @address);
while ( my @data = $it->() ) {
    $sth->execute( @data )
        or die sprintf 'Could not execute statement: %s', $sth->errstr;
}

$dbh->commit
    or die sprintf 'Could not commit updates: %s', $dbh->errstr;

$dbh->disconnect;

请注意,代码未经测试。

您可能还想阅读常见问题解答:总是引用“$vars”有什么问题?.

此外,鉴于您处理错误的唯一方法是死亡,您可能需要考虑{ RaiseError => 1 }connect调用中指定。

于 2009-11-18T20:11:43.897 回答
0

你怎么能不确定你的数组包含什么?无论如何,方法是遍历一个数组并假设其他数组具有相应的值,将它们放入插入语句中

于 2009-11-18T20:01:34.237 回答
0

另一种方法是使用散列作为中间存储区域。IE:

my $hash = {};
foreach(@array1) {
  $hash->{id} = $array1[$_];
  $hash->{name} = $array2[$_];
  $hash->{address} = $array3[$_];
}
foreach( keys %$hash ) {
  $sql = "insert into table values(?,?,?)";
  $sth = $dbh->prepare($sql) or die;
  $sth->execute($hash->{id}, $hash->{name}, $hash->{address}) or die;
}

虽然这又取决于正在同步的三个阵列。但是,您可以修改它以通过 array1 的第一个循环中的其他数组中进行值修改或检查或 grep(即:如果您在 array2 和 array3 中的值可能存储为“NN-name”和“NN-address”,其中 NN是第一个数组中的 id,您需要找到相应的值并使用 as// 正则表达式删除 NN-。不过,这取决于您的数据的结构。

另一个注意事项是查看 Class::DBI 并查看它是否可以提供更好且更面向对象的方式来获取数据。

于 2009-11-18T20:12:45.250 回答