【发布时间】:2015-11-17 22:04:52
【问题描述】:
我正在尝试将数据行批量插入到 postgres 数据库中。
我认为,我将数据填充到数组 ref 中。它是使用 perl 脚本从使用Spreadsheet::BasicReadNamedColmodule 的空格分隔文件中获取的。获取数据的代码是
$ss = new Spreadsheet::BasicReadNamedCol($xlsFileName) ||
die "Could not open '$xlsFileName': $!";
$ss->setColumns(@columnHeadings);
my @array;
my $row = 0;
while (my $data = $ss->getNextRow())
{
$row++;
push @array, "@$data";
}
下面是数组 ref 的内容。
Cristan McX 123 W State Street North Aurora IL
William Sch 123 South Third St #367 Geneva IL
Kellie xxx 123 South East St. Gardner IL
John xx 321 Princeton Ct. Frankfort IL
Peter xxxxxxx 123 N Myrtle Avenue Elmhurst IL
Izabella xxx 321 S 3rd St. #367 Geneva IL
我用来插入的 Perl DBI 代码是:
my $dbh = DBI->connect("DBI:Pg:dbname=greenthumb;host=localhost; port=5432","","", {'RaiseError' => 1});
my $sth = $dbh->prepare( 'INSERT INTO testtable (?, ?, ?, ?, ?, ?)' );
foreach(@array) { $sth->execute( @{$_} ); }
$sth->finish;
我得到的错误是:
Can't use string ("FirstName LastName BusinessName "...) as an ARRAY ref while "strict refs" in use at ./f.pl line 38.
【问题讨论】:
-
$_不是一个数组,它是一个字符串。你可能想先split它。 -
另外,如果真的是空格分隔,当它们包含空格时,你将如何区分字段,即
123 W State Street North? -
您还需要在值列表之前添加关键字
VALUES:INSERT INTO table_name VALUES ...。似乎您可能希望在循环中进行插入,该循环遍历电子表格内容,而不是字符串化和去字符串化。 -
$_不是一个数组引用,它是一个字符串。但是$data是一个数组引用。你可以说push @array, $data。
标签: perl postgresql