1

在这个脚本中,我遇到了文件名扩展的问题:如果我使用 /home/mm/test_x 它可以工作,而文件名为 /home/mm/test_x.csv 它不会:

#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use DBI;

my $table_1 = '/home/mm/test_1.csv';
my $table_2 = '/home/mm/test_2.csv';
#$table_1 = '/home/mm/test_1';
#$table_2 = '/home/mm/test_2';

my $dbh = DBI->connect( "DBI:CSV:" );
$dbh->{RaiseError} = 1;

$table_1 = $dbh->quote_identifier( $table_1 );
$table_2 = $dbh->quote_identifier( $table_2 );

my $sth = $dbh->prepare( "SELECT a.id, a.name, b.city FROM $table_1 AS a NATURAL JOIN $table_2 AS b" );

$sth->execute;
$sth->dump_results;
$dbh->disconnect;

带有文件名扩展的输出:

DBD::CSV::st 执行失败:
执行错误:没有从 /usr/local/lib/perl5/site_perl/5.12.0/x86_64-linux 调用的列 '"/home/mm/test_1.csv".id' /DBD/File.pm 在 570。

没有文件扩展名的输出:

'1'、'Brown'、'Laramie'
'2'、'Smith'、'Watertown'
2 行

这是一个错误吗?

猫 test_1.csv

id,姓名
1,棕色
2,史密斯
5,绿色

猫 test_2.csv

id,city
1,Laramie
2,Watertown
8,Springville

4

3 回答 3

3

DBD::CSV 提供了一种将您在查询中使用的表名映射到文件名的方法。相同的机制用于设置每个文件的属性,如行尾、字段分隔符等。在 DBD::CSV 文档中查找“csv_tables”。

#!/usr/bin/env perl

use warnings;
use strict;

use DBI;

my $dbh = DBI->connect("DBI:CSV:f_dir=/home/mm", { RaiseError => 1 });
$dbh->{csv_tables}->{table_1} = {
    'file' => 'test_1.csv',
    'eol' => "\n",
};
$dbh->{csv_tables}->{table_2} = {
    'file' => 'test_2.csv',
    'eol' => "\n",
};

my $sth = $dbh->prepare( "SELECT a.id, a.name, b.city FROM table_1 AS a NATURAL JOIN table_2 AS b" );

$sth->execute();
$sth->dump_results();
$dbh->disconnect();

在我的情况下,我必须指定一个行尾字符,因为我在 vi 中创建了 CSV 文件,所以它们以 Unix 行尾结尾,而 DBD::CSV 假定 DOS/Windows 行尾,而不管脚本运行的平台是什么。

于 2010-05-08T05:15:51.837 回答
0

我看起来即使这样也有效:

#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use DBI;

my $dbh = DBI->connect("DBI:CSV:f_dir=/home/mm/Dokumente", undef, undef, { RaiseError => 1, });

my $table = 'new.csv';
$dbh->do( "DROP TABLE IF EXISTS $table" );
$dbh->do( "CREATE TABLE $table ( id INT, name CHAR(64), city CHAR(64) )" );
my $sth_new = $dbh->prepare( "INSERT INTO $table( id, name, city ) VALUES ( ?, ?, ? )" );

$dbh->{csv_tables}->{table_1} = { 'file' => '/tmp/test_1.csv', 'eol' => "\n", };
$dbh->{csv_tables}->{table_2} = { 'file' => '/tmp/test_2.csv', 'eol' => "\n", };
my $sth_old = $dbh->prepare( "SELECT a.id, a.name, b.city FROM table_1 AS a NATURAL JOIN table_2 AS b" );
$sth_old->execute();

while ( my $hash_ref = $sth_old->fetchrow_hashref() ) {
    state $count = 1;
    $sth_new->execute( $count++, $hash_ref->{'a.name'}, $hash_ref->{'b.city'} );
}
$dbh->disconnect();
于 2010-05-08T06:57:40.960 回答
0

我想你可能想看看 f_ext 和 f_dir 属性。然后,您可以将您的表名分类为“test_1”和“test_2”而不使用 csv,但使用的文件将是 test_1.csv 和 test_2.csv。表名中的点的问题是点通常用于将模式与表名分开(参见 f_schema)。

于 2010-07-09T07:55:08.147 回答