gpt4 book ai didi

database - 使用 Perl,如何使用 dbh csv_tables 从标准输入读取 CSV 字符串?

转载 作者:搜寻专家 更新时间:2023-10-30 20:43:50 28 4
gpt4 key购买 nike

下面是如何使用 dbh csv_tables 将 CSV 文件读入数据库的示例。但是,我已经有了一个要与 dbh csv_tables 一起使用的 CSV 字符串。我如何从标准输入而不是文件中读取字符串?

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

# Connect to the database, (the directory containing our csv file(s))

my $dbh = DBI->connect("DBI:CSV:f_dir=.;csv_eol=\n;");

# Associate our csv file with the table name 'prospects'

$dbh->{'csv_tables'}->{'prospects'} = { 'file' => 'prospects.csv'};

# Output the name and contact field from each row

my $sth = $dbh->prepare("SELECT * FROM prospects WHERE name LIKE 'G%'");
$sth->execute();
while (my $row = $sth->fetchrow_hashref) {
print("name = ", $row->{'Name'}, " contact = ", $row->{'Contact'}. "\n");
}
$sth->finish();

干杯

利亚姆

最佳答案

DBD::CSV子类 DBD::File ,它又使用 IO::File对于 CSV 文件句柄。我们可以覆盖 DBD::CSV 的文件打开行为,将 f_dontopen 设置为 true,这样可以防止 DBD::File 打开 DBD::CSV 传入的文件。

$dbh->{'csv_tables'}->{'prospects'} = { f_dontopen => 1 };

然后,我们只需要提供我们自己的指向标准输入的 IO::File 对象。

my $io = new IO::File;
$io->fdopen(fileno(STDIN),'r');
$dbh->{'csv_tables'}->{'prospects'} = { fh => $io, f_dontopen => 1 };

把这些放在一起:

# Connect to the database
my $dbh = DBI->connect("DBI:CSV:;csv_eol=\n;");

# Associate stdin the table name 'prospects'
my $io = new IO::File;
$io->fdopen(fileno(STDIN),'r');
$dbh->{'csv_tables'}->{'prospects'} = { fh => $io, f_dontopen => 1 };

# Output the name and contact field from each row
my $sth = $dbh->prepare("SELECT * FROM prospects WHERE name LIKE 'G%'");
$sth->execute();
while (my $row = $sth->fetchrow_hashref) {
print("name = ", $row->{'name'}, " contact = ", $row->{'contact'}. "\n");
}
$sth->finish();

关于database - 使用 Perl,如何使用 dbh csv_tables 从标准输入读取 CSV 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8628690/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com